summaryrefslogtreecommitdiff
path: root/client/data/save.lua
blob: 262ee176f10a83ddb58dd05360125f1d79b85da8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
--[[
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