2016-04-25 357 views
1

我無法將表打印到與lua(我是lua新手)的文件中。如何從Lua中將表保存到文件中

這裏有一些代碼I found here來打印表;

function print_r (t) 
    local print_r_cache={} 
    local function sub_print_r(t,indent) 
     if (print_r_cache[tostring(t)]) then 
      print(indent.."*"..tostring(t)) 
     else 
      print_r_cache[tostring(t)]=true 
      if (type(t)=="table") then 
       for pos,val in pairs(t) do 
        if (type(val)=="table") then 
         print(indent.."["..pos.."] => "..tostring(t).." {") 
         sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) 
         print(indent..string.rep(" ",string.len(pos)+6).."}") 
        elseif (type(val)=="string") then 
         print(indent.."["..pos..'] => "'..val..'"') 
        else 
         print(indent.."["..pos.."] => "..tostring(val)) 
        end 
       end 
      else 
       print(indent..tostring(t)) 
      end 
     end 
    end 
    if (type(t)=="table") then 
     print(tostring(t).." {") 
     sub_print_r(t," ") 
     print("}") 
    else 
     sub_print_r(t," ") 
    end 
    print() 
end 

我不知道'print'命令的用途在哪裏,我從另一個程序中運行這個lua代碼。我想要做的是將表格保存到.txt文件。這是我嘗試過的;

function savetxt (t) 
    local file = assert(io.open("C:\temp\test.txt", "w")) 
    file:write(t) 
    file:close() 
end 

然後在print-r函數中,我在任何地方都改變它說'打印'到'savetxt'。這不起作用。它似乎沒有以任何方式訪問文本文件。任何人都可以提出另一種方法嗎

我懷疑這條線是問題;

local file = assert(io.open("C:\temp\test.txt", "w")) 

更新; 我試過編輯Diego Pino,但仍然沒有成功。我從另一個程序(爲此我沒有源代碼)運行這個lua腳本,所以我不知道輸出文件的默認目錄可能在哪裏(是否有一種方法來以編程方式獲取?)。是可能的,因爲這是從另一個程序調用有阻塞輸出的東西?

Update#2; 好像問題是這一行:

local file = assert(io.open("C:\test\test2.txt", "w")) 

我試圖改變它的「C:\ TEMP \ test2.text」,但沒有奏效。我相當確信這是一個錯誤。如果我在此之後註釋掉任何行(但將此行保留),則它仍然失敗,如果我註釋掉此行(以及任何後續的「文件」行),則代碼將運行。什麼可能導致這個錯誤?

+0

作爲後續問題;如果我不指定目錄(這似乎是在所有教程中完成的),文件在哪裏創建? – FraserOfSmeg

+0

http://lua-users.org/wiki/SaveTableToFile – hjpotter92

+0

'io.open(「C:\ temp \ test.txt」,「w」)'不會打開你的想法。 – moteus

回答

2

我不知道在哪裏的 '打印' 命令進入,

的print()輸出變爲默認的輸出文件,您可以更改與io.output([文件]),見有關查詢和更改默認輸出的詳細信息,請參閱Lua手冊。

在哪裏的文件,如果我不指定目錄

通常它會在當前目錄土地獲得創建。

2

您的print_r函數打印出一張表格到stdout。你想要的是將print_r的輸出打印到文件中。更改print_r函數,以便打印到文件描述符而不是打印到stdout。也許這樣做最簡單的方法是將文件描述符傳遞到print_r並覆蓋print功能:

function print_r (t, fd) 
    fd = fd or io.stdout 
    local function print(str) 
     str = str or "" 
     fd:write(str.."\n") 
    end 
    ... 
end 

print_r的其餘部分不需要任何改變。

稍後在savetxt請致電print_r將表格打印到文件中。

function savetxt (t) 
    local file = assert(io.open("C:\temp\test.txt", "w")) 
    print_r(t, file) 
    file:close() 
end 
0

1.

require("json") 
result = { 
    "ip"]="192.168.0.177", 
    ["date"]="2018-1-21", 
} 

local test = assert(io.open("/tmp/abc.txt", "w")) 
result = json.encode(result) 
test:write(result) 
test:close() 


require("json") 
local test = io.open("/tmp/abc.txt", "r") 
local readjson= test:read("*a") 
local table =json.decode(readjson) 
test:close() 
print("ip: " .. table["ip"]) 

2.Another方式: http://lua-users.org/wiki/SaveTableToFile

表保存到文件 功能table.save(TBL,文件名)

負載表從文件 函數table.load(sfile)

相關問題