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?

7

3 Answers

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.

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
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:

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

Load Table from File function table.load( sfile )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest