table to lua file
Posted: Wed Jun 07, 2023 8:39 am
Ok here is the thing. I thought about using json and other types of serialization of a typical table that i needed to be stored as data table only (this means no functions, no special data or pointers on images etc) into a .lua file. I looked at the serialization libraries and they were huge around 10kB.
So this is the smallest version i share here. Store it into utils.lua or copy into your own library path.
Then use it this way:
Hope it helps you if you for some reason do not want to use json or xml to store table data per file.
So this is the smallest version i share here. Store it into utils.lua or copy into your own library path.
Code: Select all
local Utils={}
function Utils.serialize(o,str,indent)
indent=indent or 1
local t=type(o)
if t=="function" then
-- skip
elseif t=="boolean" then
str=str..tostring(o)..",\n"
elseif t=="number" then
str=str..o..",\n"
elseif t=="string" then
str=str..string.format("%q",o)..",\n"
elseif t=="table" then
if indent==1 then
str="return {\n"
else
str=str.."{\n"
end
local spaces=string.rep(" ",indent)
for k,v in pairs(o) do
local tv=type(v)
if tv~="function" then
local tk=type(k)
if tk=="string" then
str=str..spaces..k.."="
elseif tk=="number" then
str=str..spaces.."["..tostring(k).."]="
end
str=Utils.serialize(v,str,indent+1)
end
end
if indent>1 then
local espaces=string.rep(" ",indent-1)
str=str..espaces.."},\n"
else
str=str.."}\n"
end
else
error("cannot serialize a "..tostring(t))
end
return str
end
return Utils
Code: Select all
local Utils=require("src/utils")
-- convert table tbl1 to string str
local tbl1={width=150,height=160,stats={str=15,dex=18,con=10},hitpoints=50,items={[1]="apple",[2]="corn"},}
local str=Utils.serialize(tbl1)
print(str)
-- write string of tbl1 to tbl1.lua in love 2D save folder in appdata
love.filesystem.write("tbl1.lua",str)
-- get the lua code for tbl1 from tbl1.lua file as a pointer chunk
local chunk=love.filesystem.load("tbl1.lua")
-- now if you call it like this you get back your stored table. then check it in debugger to see if it is correctly restored
local tbl=chunk()