Printing Table to Text File

Does anyone know of a way to store a table in a file and use it later?

example would be something like this
[lua]
local stuff = {}

function savetable(tbl)
file.Write(“table.txt”, tbl)
end
function loadtable(tbl)
if file.Exists(“table.txt”) then
stuff = (file.Read(“table.txt”))
end
end
[/lua]

Of course that wouldn’t work, so does anyone know of a way to make it work?

I made this a while ago.
It will turn your table into a string and it will turn that string back to a table.

[editline]asd[/editline]
Chessnut suggested util. functions.
Those two convert to and from a human-readable format, but are restricted to simple data types.
vON has much more possibilities, but the output is not very human-readable.

glon.encode and glon.decode

util.TableToKeyValues(<table>) - Human Readable
glon.encode(<table>) - Not readable.

util.KeyValuesToTable(<read stuff>)
glon.decode(<read stuff>)

I could never get KeyValues to work quite right. (also, I want it to be human readable and editable) Do you have an example or something you could show me?

[editline]3rd September 2012[/editline]

[lua]stuff = (file.Exists(“table.txt”) and KeyValuesToTable(file.Read(“table.txt”)) or {} )

function addtotable(args)
if not table.HasValue(stuff, args) then
table.insert(stuff , args)
file.Write(“table.txt” , TableToKeyValues(stuff))
end
end[/lua]

This wouldn’t work quite right for me, which confused me a ton (I tried a lot to get it to work, nothing did).

Depending on the structure of your table, my INI parser might interest you.

For example, You could have the table :

[Lua]local Table = {
[“SomeName”] = {

	["SomeVar"] = "Hey",
	["SomeVar2"] = "Hey",
	["SomeVar3"] = "Hey",
	["SomeVar4"] = "Hey"
	
},
["SomeOtherName"] = {

	["SomeOtherVar"] = "Hey",
	["SomeOtherVar2"] = "Hey",
	["SomeOtherVar3"] = "Hey",
	["SomeOtherVar4"] = "Hey"
	
}

}
[/lua]

using my library you could turn it into this:




[SomeName]
	
SomeVar = "Hey"
SomeVar2 = "Hey"
SomeVar3 = "Hey"
SomeVar4 = "Hey"
		
[SomeOtherName]
	
SomeOtherVar = "Hey"
SomeOtherVar2 = "Hey"
SomeOtherVar3 = "Hey"
SomeOtherVar4 = "Hey"


using this

[Lua]

local Parser = INIParser.New( )
Parser.Data = MyTable

print( tostring( Parser ) )

[/lua]

and get it back to it’s Lua form by doing

[lua]
local Parser = INIParser.New( The_String_That_Got_Outputted )
PrintTable( Parser:GetData( ) )
[/lua]

My tables are mainly just basic {“item 1”, “item 2”, “item 3”}. But I’ll look into that.

[editline]3rd September 2012[/editline]

It doesn’t really seem like the parser would be necessary for this, I really would rather just see an example of KeyValues working correctly.