Making Savegames
Posted: Sun Oct 04, 2015 4:34 pm
Can Anyone help me I'm trying to make a game that saves both the settings and the Highscores.
Code: Select all
function table.save(tab,name)
name=name or "test"
local output="local "..name.."=\n"
local function ergodic(target,time)
time=time+1
output=output.."{\n"
for k,v in pairs(target) do
output=output .. string.rep("\t",time)
if type(v)=="table" then
if type(k)=="number" then
output=output.."["..k.."]".."="
elseif type(k)=="string" then
output=output.."[\""..k.."\"]="
end
ergodic(v,time)
output=output .. string.rep("\t",time)
output=output.."},\n"
elseif type(v)=="string" then
if type(k)=="number" then
output=output.."["..k.."]".."=\""..v.."\",\n"
elseif type(k)=="string" then
output=output.."[\""..k.."\"]=\""..v.."\",\n"
end
elseif type(v)=="number" then
if type(k)=="number" then
output=output.."["..k.."]".."="..v..",\n"
elseif type(k)=="string" then
output=output.."[\""..k.."\"]="..v..",\n"
end
end
end
end
ergodic(tab,0)
output=output.."}\n return "..name
return output
end
Note that that method doesn't deal with cycles or some other types of data: strings containing ", nan, inf, keys that aren't strings or numbers, values that aren't tables, strings or numbers (like booleans), ...Alexar wrote:i wrote an easy method, just copy the table you need into file as lua script. the output is string, you can print it to test.
yeah, I forgot boolean. i still use binser or bintable in my own project. but this is an easy way to convert table to readable string.Robin wrote: Note that that method doesn't deal with cycles or some other types of data: strings containing ", nan, inf, keys that aren't strings or numbers, values that aren't tables, strings or numbers (like booleans), ...
There are plenty of good serialisation libraries available, I recommend using one of those (especially binser or one of my libraries: Ser, Lady or Smallfolk).