我的问题是在NodeMCU开发工具包中读取文本文件(位于我的计算机中) . 我能够使用Lua脚本读取Ubuntu终端中的文件内容 . 在这里,我分享了我一直用于阅读的代码 . 两者在Ubuntu终端都运行良好 .
第一:
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
第二个:
local fileContent = read_file("output.txt");
print (fileContent);
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'output.txt'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
当我将代码发送到NodeMCU,使用Esplorer发送代码时,我的问题就出现了 . 但错误发生如下:
attempt to index global 'io' (a nil value)
stack traceback:
applicationhuff.lua:5: in function 'file_exists'
applicationhuff.lua:13: in function 'lines_from'
applicationhuff.lua:23: in main chunk
[C]: in function 'dofile'
stdin:1: in main chunk
我的一般目的实际上是读取这些数据并通过MQTT协议将其发布到Mosquitto Broker . 我是这些主题的新手 . 如果有人能解决我的问题,将不胜感激 . 谢谢你的帮助...
1 回答
NodeMCU没有
io
库 . 因此,索引io
会出错,这是一个零值 .没有冒犯,但有时我想知道你们实际上是如何设法找到通往StackOverflow的方式,甚至在不知道如何进行基本网络研究的情况下编写一些代码 .
https://nodemcu.readthedocs.io/en/master/en/lua-developer-faq/
https://nodemcu.readthedocs.io/en/master/en/modules/file/
我希望有足够的帮助......