[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua, LuaJIT2 and differences with the length operator
- From: Roberto Ierusalimschy <roberto@...>
- Date: Tue, 4 Jan 2011 16:16:59 -0200
> On Tue, Jan 4, 2011 at 08:41, Dirk Laurie <dpl@sun.ac.za> wrote:
> > On Tue, Jan 04, 2011 at 03:18:29PM +0200, Leo Razoumov wrote:
> >> Lua provides no good way to test whether a given array has holes or
> >> not.
> > Not Lua's job. Your job.
> >
>
> And how exactly I am supposed to do this job? E.g., how can I test
> that an array t coming my way from someone else's library has no
> holes?
How do you test that a tree coming your way from someone else is
actually a tree? You do not. This is part of the API. This is what
people call "documentation".
If someone gives you a table with no extra information, you do not even
know whether the table has useful stuff in numeric indices, so why
bother to use '#'? But if you know what the table is, it should be part
of what you know whether it may have holes. (If so, it also should be
part of what you know how to get its real size.)
But if you really want to check, just to make sure, this is how you
can do your job. I assume you know at least that the value is a
table. Change as needed to your specific circumstances:
function noholes (t)
local n = #t
local i = 0
for k in pairs(t) do
if type(k) == 'number' then
if math.floor(k) == k and 1 <= k and k <= n then
i = i + 1
else
return false
end
end
end
return (i == n)
end
Not so hard, is it?
Now, can we stop this discussion and move to something more productive?
-- Roberto