--[[ Functions for turning a table into lua code that will re-create the table. ]] local fn = require("fn") local tts = {} function tts.table_to_string(tbl) --Collect all of our tables first, --so that we don't break when we have recursive tables. local tables = {} local table_order = {} local function tables_helper(t) tables[t] = #table_order + 1 table_order[#table_order + 1] = t for k,v in pairs(t) do if type(k) == "table" and not tables[k] then tables_helper(k) end if type(v) == "table" and not tables[v] then tables_helper(v) end end end tables_helper(tbl) --Get the string representation of an element local errfun = function(e) error("Cannot format a " .. type(e)) end local rep_map = { --things we can format number = function(e) return string.format("%f",e) end, string = function(e) return string.format("%q",e) end, boolean = function(e) return e and "true" or "false" end, table = function(e) assertf(tables[e] ~= nil,"Could not find dependency table %s",tostring(e)) return string.format("table_%d",tables[e]) end, --things we can't format ["function"] = errfun, coroutine = errfun, file = errfun, userdata = errfun, --nil can never happen } local sb = {} --Create all the variables first, so that recursive tables will work for n,_ in pairs(table_order) do sb[#sb + 1] = string.format("local table_%d = {}",n) end --Go backwards through tables, since that should be the --"dependency" order for i = #table_order, 1, -1 do -- -1 is needed in case #table_order == 0 local tstr = {} local this_table = table_order[i] for k,v in pairs(this_table) do tstr[#tstr + 1] = string.format("table_%d[%s] = %s",i,rep_map[type(k)](k), rep_map[type(v)](v)) end sb[#sb + 1] = table.concat(tstr,"\n") end sb[#sb + 1] = "return table_1" return table.concat(sb,"\n\n"); end return tts