Created
January 2, 2011 22:38
-
-
Save EmmanuelOga/762890 to your computer and use it in GitHub Desktop.
A table that can be iterated over the array part and the non integer keys separatedly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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