[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Why no for table-iterator like e. g. "hashpairs"?
- From: Francisco Olarte <folarte@...>
- Date: Fri, 1 Nov 2019 17:47:48 +0100
On Fri, Nov 1, 2019 at 4:27 PM bil til <email@example.com> wrote:
> ... this is a nasty example, as then the table contains nil...
Tables in lua can not contain nil. This one of the things
differentiating local variables and table "slots" ( globals are inside
a table ). In fact, you assign nil to a table index to delete it.
> So this is a "really nasty table" now... it has nils distributed nicely in
> its key-value range 1...1000, and #t just gives some sort of
> "estimated length".
That is because it is not a sequence. Anyway, #t does not give an
stimated length, it gives what is defined in the manual:
The length operator applied on a table returns a border in that table.
A border in a table t is any natural number that satisfies the
(border == 0 or t[border] ~= nil) and t[border + 1] == nil
In words, a border is any (natural) index in a table where a non-nil
value is followed by a nil value (or zero, when index 1 is nil).
And, at the start of the next line:
"A table with exactly one border is called a sequence."
> ... so this ran nicely up to 1000 without
> any error message, all nicely sorted for the
> number indices...
I think this is because you have a "dense" table and, IIRC, in lua 5.3
the hash value of an integer is itself ( which is open to some sort of
attacks, but good for many things ). OTOH this has the nice property
of easy enumeration of relatively dense tables.
Trying to prove my point I did a simple check in5.3.3 ( its the one
which comes with debian, but I suspect results would be the same for
5.3.5 ) and succeeded at the firs attempt not only to create an out of
order enumeration, but curiously an strictly reversed one:
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> for k,v in pairs(t) do print(k,v) end
I suspect a simple analysis can reveal I'm either getting collisions (
unlikely ) or they are their own hashes and the table size is 4 or
> for k,v in pairs(t) do print(k,v, k%4, k%8, k%16) end
44444 4 0 4 12
33333 3 1 5 5
22222 2 2 6 14
11111 1 3 7 7
Reading the source, it's quite commented, or asking a more
knowledgeable person may shed more light.