FraserOfSmeg
FraserOfSmeg

Reputation: 1148

How to save a table to a file from Lua

I'm having trouble printing a table to a file with lua (and I'm new to lua).

Here's some code I found here to print the table;

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

I have no idea where the 'print' command goes to, I'm running this lua code from within another program. What I would like to do is save the table to a .txt file. Here's what I've tried;

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

Then in the print-r function I've changed everywhere it says 'print' to 'savetxt'. This doesn't work. It doesn't seem to access the text file in any way. Can anyone suggest an alternative method?

I have a suspicion that this line is the problem;

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

Update; I have tried the edit suggested by Diego Pino but still no success. I run this lua script from another program (for which I don't have the source), so I'm not sure where the default directory of the output file might be (is there a method to get this programatically?). Is is possible that since this is called from another program there's something blocking the output?

Update #2; It seems like the problem is with this line:

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

I've tried changing it "C:\temp\test2.text", but that didn't work. I'm pretty confident it's an error at this point. If I comment out any line after this (but leave this line in) then it still fails, if I comment out this line (and any following 'file' lines) then the code runs. What could be causing this error?

Upvotes: 4

Views: 20724

Answers (3)

Brian
Brian

Reputation: 33

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.Another way: http://lua-users.org/wiki/SaveTableToFile

Save Table to File function table.save( tbl,filename )

Load Table from File function table.load( sfile )

Upvotes: 2

Diego Pino
Diego Pino

Reputation: 11596

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

Upvotes: 3

Vlad
Vlad

Reputation: 5857

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.

Upvotes: 2

Related Questions