Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A table that can be iterated over the array part and the non integer keys separatedly
local arrayTable do
local function isinteger(num)
if type(num) == "number" then
local _, f = math.modf(num)
return f == 0
else
return false
end
end
arrayTable = function(initial)
local table = { ___array = {}, ___table = {} }
local metatable = {
__index = function(_, key)
return rawget(table.___table, key) or rawget(table.___array, key)
end,
__newindex = function(_, key, val)
if isinteger(key) then
return rawset(table.___array, key, val)
else
return rawset(table.___table, key, val)
end
end
}
table = setmetatable(table, metatable)
for k, v in pairs(initial) do
table[k] = v
end
return table
end
end
function at_ipairs(at)
return ipairs(at.___array)
end
function at_pairs(at)
return pairs(at.___table)
end
a = arrayTable{1, 2, a = 1}
a[1.5]=1.5
a[3] = "a"
a["b"] = 2
a[5] = "c"
a["c"] = 3
a[4] = "b"
for i, v in at_ipairs(a) do
print(i, v)
end
print('---------')
for i, v in at_pairs(a) do
print(i, v)
end
output = [[
▸ lua arrayandtable.lua
1 1
2 2
3 a
4 b
5 c
---------
a 1
c 3
1.5 1.5
b 2
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment