-
Notifications
You must be signed in to change notification settings - Fork 3
/
autotable.lua
47 lines (43 loc) · 940 Bytes
/
autotable.lua
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
do
local auto, assign
function auto(tab, key)
if getmetatable(tab).dim > 1 then
return setmetatable({}, {
__index = auto,
__newindex = assign,
dim = getmetatable(tab).dim - 1,
parent = tab,
key = key
})
else
return nil
end
end
function assign(tab, key, val)
if val ~= nil then
local oldmt = getmetatable(tab)
local dim = oldmt.dim
oldmt.parent[oldmt.key] = tab
setmetatable(tab, {__index = auto, dim = dim})
tab[key] = val
end
end
function table.autotable(dim)
return setmetatable({}, {__index = auto, dim = dim})
end
end
--[[
m = table.autotable(2)
m[1][2] = 'x'
m[3][4] = 'y'
assert(m[1][2] == 'x')
assert(type(m[2]) == 'table')
assert(type(m[2][3]) == 'nil')
assert(type(auto) == 'nil')
assert(type(assign) == 'nil')
for i,inner in pairs(m) do
for j,v in pairs(inner) do
print(i, j, v)
end
end
--]]