raidho36 wrote:But then "length" is a bad name as well because array could be longer than this value.
Bad or not, that's still its name. If you have a better suggestion for a name, pitch it to the Lua authors. It would be confusing if users started calling it by something other than its name.
Also, an array
can't be longer than this value if "length" in this context simply means the index of any non-nil element preceding a nil, and nothing more. The word can mean whatever the authors want it to mean; they probably just found it to be a good fit for that concept (I've never seen any better suggestions, anyway).
So the only way to reliably iterate through array with holes is to use "pairs". Then again, it ignores holes and includes literal indices.
And the order of iteration is not defined, and it won't JIT.
Alternatively, you keep track of its real length elsewhere.
Yeah, that's the usual approach to storing sparse arrays. Generally the "real" length is stored in the same table in a key named "n" (which has some historical precedent because of its special meaning to the deprecated/removed "table.getn" and "table.setn" functions).
pgimeno wrote:In further support of this, in LuaJIT:
Code: Select all
print(#{1, 2, nil, 4, 5}) -- prints 5
print(#{1, 2, 3, nil, 5}) -- prints 3
Right, and it's implementation-dependent; as I recall PUC Lua gives different results in at least one of those cases. Anyway, bottom line is # won't give predictable results on sparse arrays.