-- ilua.lua
-- This file is executed with the global "ilua" table already defined
-- serialization support function
function ilua.basicSerialize (o)
if type(o) == "number" then
return tostring(o)
else -- assume it is a string
return string.format("%q", o) end
end
-- save a table to current I/O stream
function ilua.saveTable (name, value, saved)
saved = saved or {} -- initial value
io.write(name, " = ")
if type(value) == "number" or type(value) == "string" then
io.write(ilua.basicSerialize(value), "\n")
elseif type(value) == "table" then
if saved[value] then -- value already saved?
io.write(saved[value], "\n") -- use its previous name
else
saved[value] = name -- save name for next time
io.write("{}\n") -- create a new table
for k,v in pairs(value) do -- save its fields
k = ilua.basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
ilua.saveTable(fname, v, saved)
end
end
else
error("cannot save a " .. type(value))
end
end
-- Users can add fields to 'ilua._DATA' table
-- as-needed for perstistent storage between sessions.
-- Supported types include number, string, and table.
-- User must call 'ilua.saveData' function to save data
-- as a script file named 'data.lua'. The 'ilua._DATA'
-- table is recreated by calling 'ilua.loadData' or by
-- simply executing 'data.lua'.
function ilua.saveData()
ilua._DATA = ilua._DATA or {}
local f = io.open("data.lua", "w")
io.output(f) -- prepare to write
io.write("-- data.lua\n\n")
ilua.saveTable("ilua._DATA", ilua._DATA)
f:close()
io.output(io.stdout) -- restore stdout
end
-- load the ilua._DATA table from file 'data.lua'
function ilua.loadData()
local f = io.open("data.lua", "r")
if f == nil then -- does file exist?
ilua.saveData() -- create if necessary
else
f:close() -- close existing file
end
io.input(io.stdin) -- restore stdin
dofile("data.lua") -- run the script
end
-- instantiate ilua._DATA table from file 'data.lua'
ilua.loadData()