BroccoliRaab wrote: ↑Mon Jul 10, 2017 11:31 pmI was worried about performance and wasn't sure how to implement the usage of table.concat
Performance shouldn't be an issue if you're just saving the game's options/player progress.
If you want to save more complicated things, then you need better serialization.
BroccoliRaab wrote: ↑Mon Jul 10, 2017 11:31 pmBut thank you for bringing up problems that I was unaware of and people that may choose to use this library may have potentially also been unaware of.
Sure, no worries.
Note that if your code is NOT supposed to support cycles or weak keys, then you need an assertion or some sort of error message.
Like I said, saving your options as a flat list of key-value pairs is much cleaner, here's an example using Lua's "io" module:
Code: Select all
function format(v)
local t = type(v)
if t == "string" then
v = string.format("%q", v)
elseif t == "number" or t == "boolean" then
v = tostring(v)
else
error("unsupported variable type:"..t)
end
return v
end
function save(t, fn)
-- assumes the directory exists, will fail otherwise
local f = io.open(fn, "w")
if f == nil then
return false
end
f:write("return {\n")
for k, v in pairs(t) do
k = format(k)
v = format(v)
local out = string.format('[%s]=%s,\n', k, v)
f:write(out)
end
f:write("}")
f:close()
return true
end
Alternative using table.concat:
Code: Select all
function format(v)
local t = type(v)
if t == "string" then
v = string.format("%q", v)
elseif t == "number" or t == "boolean" then
v = tostring(v)
else
error("unsupported variable type:"..t)
end
return v
end
function serialize(t, out)
out = out or {}
for k, v in pairs(t) do
k = format(k)
v = format(v)
local kv = string.format('[%s]=%s', k, v)
table.insert(out, kv)
end
return out
end
function save(t, fn)
local out = serialize(t)
local s = "return {\n"..table.concat(out, ",\n").."}"
-- todo: save to file
end