使用Lua读取位于计算机上的文本文件和NodeMCU

时间:2017-01-05 19:22:05

标签: lua nodemcu esplorer

我的问题是在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 个答案:

答案 0 :(得分:1)

enter image description here

enter image description here

NodeMCU没有io库。因此,索引io会出错,这是一个零值。

没有冒犯,但有时我想知道你们实际上是如何找到通往StackOverflow的方式,甚至在不知道如何进行基本网络研究的情况下编写一些代码。

https://nodemcu.readthedocs.io/en/master/en/lua-developer-faq/

  

固件已替换了一些不对齐的标准Lua模块   具有ESP8266特定版本的SDK结构。对于   例如,标准的io和os库不起作用,但已经存在   很大程度上被NodeMCU节点和文件库取代。

https://nodemcu.readthedocs.io/en/master/en/modules/file/

  

文件模块提供对文件系统及其个人的访问   文件。

我希望有足够的帮助......