[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: I dont understand all those discussions.
- From: Martin <eden_martin_fuhrspam@...>
- Date: Thu, 21 Jul 2016 23:43:17 -0700
On 16-07-21 12:50 PM, Russell Haley wrote:
> Perhaps posting an example for people to follow would help lessen some
> of the "noise"?
As stated somewhere earlier, to implement arrays with nils inside you
just need to define __len metamethod. This sketch demonstrates one of
possible implementations of this idea.
-----
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
-----