summaryrefslogtreecommitdiff
path: root/util.lua
blob: 6cba798fc6032ccb551d5f1b6eeb995bda5e7d47 (plain) (blame)
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
65
66
67
68
69
70
71
72
73
-- Some useful Lua functions.

util = {}

function util.key_ordered_pairs(t, f)
	local a = {}
	for n in pairs(t) do table.insert(a, n) end
	table.sort(a, f)
	local i = 0
	local iter = function ()
		i = i + 1
		if a[i] == nil then return nil
		else return a[i], t[a[i]]
		end
	end
	return iter
end

local function write_imp(name, t, file, indent)
	for i = 1, indent do
		file:write("\t")
	end
	local ty = type(t)
	if name then
		file:write(string.format("%s = ", name))
	end
	if ty == 'table' then
		file:write("{\n")
		local del = false
		if #t > 0 then
			for i, v in ipairs(t) do
				write_imp(nil, v, file, indent + 1)
				file:write(',\n')
			end
			del = true
		else
			for k, v in util.key_ordered_pairs(t) do
				write_imp(tostring(k), v, file, indent + 1)
				file:write(',\n')
				del = true
			end
		end
		if del then
			file:seek('cur', -2) -- Wipe the last comma
		end
		file:write('\n')
		for i = 1, indent do
			file:write("\t")
		end
		file:write("}")
	elseif ty == 'string' then
		file:write(string.format("'%s'", t))
	else
		file:write(string.format("%s", tostring(t)))
	end
end

function util.write_table(kname, t, fname)
	local file = io.open(fname, 'w')
	write_imp(kname, t, file, 0)
end

function util.deep_copy(tab)
	local r = {}
	for k, v in pairs(tab) do
		local nv
		if type(v) == 'table' then
			nv = util.deep_copy(v)
		else nv = v end
		r[k] = nv
	end
	return r
end