~nch/gamelog

ref: 75432213d3972f26c03ef636da68ed482f0ac908 gamelog/tuple.lua -rw-r--r-- 728 bytes View raw
75432213 — nc refactoring debug code out a bit 5 months ago
                                                                                
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
local tuples = {}
local tuple_meta = {}
local val_slot = {} -- uniq identifier

local function find_tuple(...)
	local a = {...}
	local t = tuples
	for i=1, #a do
		if t[a[i]] == nil then t[a[i]] = {} end
		t = t[a[i]]
	end
	if t[val_slot] == nil then t[val_slot] = setmetatable({...}, tuple_meta) end
	return t[val_slot]
end

tuple_meta.__index={
	update = function(this, i, new_v)
		local s = {}
		for j=1, #this do
			if j == i then
				table.insert(s, new_v)
			else
				table.insert(s, this[j])
			end
		end
		return find_tuple(table.unpack(s))
	end}

tuple_meta.__tostring = function(t)
	local s = {}
	for i=1, #t do
		table.insert(s, tostring(t[i]))
	end
	return '(' .. table.concat(s, ', ') .. ')'
end

return find_tuple