[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: new "empty" value/type in Lua?
- From: Luis Carvalho <lexcarvalho@...>
- Date: Tue, 2 Jul 2013 20:34:43 -0400
> Is something like this enough? (Note that 'n' is *not* hidden; I do
> not think hidden stuff is good in the end...)
Agreed. I had a very similar version, but required that only integer keys can
be set in __newindex and setlength is implemented through __call:
local type, floor, pack, setmetatable, rawset =
type, math.floor, table.pack, setmetatable, rawset
_ENV = nil
local nexti = function (t, i)
if i < t.n then
i = i + 1
return i, t[i]
end
end
local mt = {
__len = function (t) return t.n end,
__ipairs = function (t) return nexti, t, 0 end,
__newindex = function (t, k, v)
if type(k) == "number" and k > 0 and k == floor(k) then
if k > t.n then t.n = k end -- grow?
return rawset(t, k, v)
end
end,
__call = function (t, n) -- resize?
if type(n) == "number" and n >= 0 and n == floor(n) then
if n < t.n then
for i = n + 1, t.n do t[i] = nil end -- clean up
end
t.n = n
end
return t.n
end,
}
return function (...)
return setmetatable(pack(...), mt)
end
Cheers,
Luis
--
Computers are useless. They can only give you answers.
-- Pablo Picasso
--
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'