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

我的问题是关于在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

当我使用Esplorer将代码发送到NodeMCU时,我的问题就出现了,但是错误就像这样:

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中。我对这些话题还很新。如果有人能解决我的问题,我将非常感激。感谢您的帮助...

点赞
用户2858170
用户2858170

在此输入图片描述

在此输入图片描述

NodeMCU没有io库,所以对io进行索引会导致错误,因为它是一个空值。

不冒犯,但我有时会想知道你们这些人如何在不知道如何进行基本网络研究的情况下找到 StackOverflow 并编写代码。

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

固件已经用 ESP8266 特定版本替换了一些与 SDK 结构不对齐的标准 Lua 模块。例如,标准的 ioos 库不起作用,但已经被 NodeMCU 的节点和文件库广泛替换。

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

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

我希望这足够了帮助...

2017-01-05 22:03:33