Re: Mini Functions Repository
Posted: Mon Jun 13, 2016 8:35 am
Hey ZBoyer, those functions reminded me of my first data serializer:-
This works recursively on any table and will ignore function values, not great for saving objects but I use ECS so objects shouldn't have functions associated with them. Works great for save games though it can make some pretty large files.
(Does anyone else keep opening the 'save as' window when adding code on here? It seems I now instinctively hit Ctrl + s every time I finish typing a line! )
Code: Select all
-- Returns a single string gathered recursively from the table 't' The spacing value is for indentation as I am a stickler for human readable serialization just leave it as nil when you call the function and it'll indent at every new table it finds.
function serialize(t, spacing)
if spacing == nil then spacing = "" end
local str = "{ \n"
spacing = spacing.." "
for k, v in pairs(t) do
local key = k.." = "
if tonumber(k) then
key = ""
end
if type(v) == "string" then
str = str..spacing..key.."'"..v.."',\n"
elseif type(v) == "number" then
str = str..spacing..key..tostring(v)..",\n"
elseif type(v) == "table" then
str = str..spacing..key..serialize(v, spacing)..",\n"
end
end
str = str..spacing.."}"
return str
end
--To save the data to a file then I tend to just add "return" to the start of the string so it can be loaded as a pure lua file.
function save(data, folder, label)
love.filesystem.createDirectory(folder)
local save = love.filesystem.newFile(folder.."/"..label..".lua", "w")
save:write("return "..serialize(data))
save:close()
end
(Does anyone else keep opening the 'save as' window when adding code on here? It seems I now instinctively hit Ctrl + s every time I finish typing a line! )