如何将表保存到Lua中的文件

时间:2016-04-25 07:51:47

标签: io 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函数中,我在任何地方都改变了'print'到'savetxt'。这不起作用。它似乎不以任何方式访问文本文件。有人可以提出另一种方法吗?

我怀疑这条线是问题所在;

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

更新 我尝试了Diego Pino建议的编辑,但仍然没有成功。我从另一个程序(我没有源代码)运行这个lua脚本,所以我不确定输出文件的默认目录可能在哪里(是否有一种以编程方式获取此文件的方法?)。有可能因为从另一个程序调用了阻塞输出的东西吗?

更新#2; 似乎问题在于这一行:

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

我已经尝试将其更改为“C:\ temp \ test2.text”,但这不起作用。我非常有信心这是一个错误。如果我在此之后注释掉任何一行(但是留下这一行)那么它仍然会失败,如果我注释掉这一行(以及任何后面的“文件”行),那么代码就会运行。可能导致此错误的原因是什么?

3 个答案:

答案 0 :(得分:2)

I have no idea where the 'print' command goes to,

print() output goes to default output file, you can change that with io.output([file]), see Lua manuals for details on querying and changing default output.

where do files get created if I don't specify the directory

Typically it will land in current working directory.

答案 1 :(得分:2)

Your print_r function prints out a table to stdout. What you want is to print out the output of print_r to a file. Change the print_r function so instead of printing to stdout, it prints out to a file descriptor. Perhaps the easiest way to do that is to pass a file descriptor to print_r and overwrite the print function:

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

The rest of the print_r doesn't need any change.

Later in savetxt call print_r to print the table to a file.

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

答案 2 :(得分: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.另一种方式: http://lua-users.org/wiki/SaveTableToFile

将表保存到文件 function table.save(tbl,filename)

从文件加载表 function table.load(sfile)