如何从Lua将表格保存到文件中

4

我在使用lua打印表格到文件时遇到了困难(我是lua新手)。

这里有一些我找到的代码可以用来打印表格;

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”,但没有成功。我相当有信心这是一个错误点。如果我注释掉此行之后的任何行(但保留此行),则仍然失败;如果我注释掉此行(和任何后续的'file'行),则代码运行。可能是什么导致了这个错误?


http://lua-users.org/wiki/SaveTableToFile - hjpotter92
io.open("C:\temp\test.txt", "w") 打开的不是你想象的那个。 - moteus
@moteus 你是什么意思? - FraserOfSmeg
"\t" 是制表符,请尝试使用 "\t"。另外,如果要将数据保存到文件中,您可以使用一些现有的序列化库,如json/msgpack/cbor/serpent等。为什么需要编写新的库呢? - moteus
我已经尝试了 \t - 仍然失败。我能否将序列化库包含在一个单独的 Lua 文件中,然后从我无法控制的程序中调用它? - FraserOfSmeg
显示剩余2条评论
3个回答

3

您的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

2

我不知道'print'命令输出到哪里了。

print()的输出会默认写入到输出文件中,你可以使用io.output([file])来更改输出文件,详见Lua手册。

如果我没有指定目录,文件会被创建在哪里?

通常会被创建在当前工作目录。


2
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()

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 )


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接