2017-01-05 38 views
0

我的問題是關於讀取NodeMCU開發工具包中的文本文件(位於我的計算機中)。我能夠使用Lua腳本讀取Ubuntu終端中的文件內容。在這裏,我分享了我一直用來閱讀的代碼。兩者在Ubuntu終端上都運行得很好。使用Lua讀取位於計算機上的帶NodeMCU的文本文件

第一招:

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 

我的一般目的實際上是讀取這些數據並將其發佈到蚊子B roker通過MQTT協議。我對這些主題很陌生。如果任何人都可以處理我的問題,將不勝感激。感謝您的幫助......

回答

1

enter image description here

enter image description here

NodeMCU沒有一個io庫。因此,索引io時出現錯誤,該值爲零。

沒有冒犯,但有時我想知道你們是如何設法找到你的方式來到StackOverflow,甚至寫一些代碼而不知道如何做基本的網絡研究。

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

固件已經取代不與特定的ESP8266版本的SDK結構對齊 以及一些標準的Lua模塊。例如,對於 示例,標準io和os庫不起作用,但大部分已被 替換爲NodeMCU節點和文件庫。

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

文件模塊提供了訪問文件系統及其個人 文件。

我希望這是足夠的幫助......

+0

大多數這個答案的回答是,這不是問(如何做一個谷歌搜索)的問題。作爲評論,這些信息可能會更好,因此對問題的回答很容易識別。 此外,「我不知道我不知道的」效果可能會導致初學者使用無效的谷歌查詢,這對於具有更多經驗的人來說似乎是顯而易見的。 –

+4

@KelsonB​​all我不同意。網絡搜索可能在10年前無效。但是今天我甚至可以點擊一個麥克風圖標,然後問我的電腦「如何讀取nodemcu中的文件?」它會給我帶有例子的怪異答案......這是如何無效的?作爲程序員獲取這些知識也不需要很多經驗。實際上你甚至不需要知道谷歌。引用開發工具包實際附帶的文檔就足夠了... – Piglet

+2

@Piglet我完全同意你的挫敗感,但無論出於何種原因,我都會繼續努力: -/ –