Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RussellHaley/86fc2a31dc7ac9103bde3080f22ff5ef to your computer and use it in GitHub Desktop.
Save RussellHaley/86fc2a31dc7ac9103bde3080f22ff5ef to your computer and use it in GitHub Desktop.
Lua Table With "holes" example
local empty_func = function() end
--( Implement yourself:
local assert_table = empty_func
local is_number = function() return true end
local is_integer = function() return true end
--)
local get_max_idx =
function(t)
assert_table(t)
local result
for k, v in pairs(t) do
if is_number(k) and is_integer(k) then
if not result or (k > result) then
result = k
end
end
end
return result
end
local length_func =
function(t)
local mt = getmetatable(t)
return mt.array_length
end
local to_array =
function(t, length)
length = length or get_max_idx(t) or 0
setmetatable(
t,
{
is_array = true,
array_length = length,
__len = length_func,
}
)
end
-- Demo:
local t = {nil, nil, 3, nil, 5}
to_array(t)
for i = 1, #t do
print(i, t[i])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment