Discussion:
about array lenght
哎呀
2014-08-21 03:32:42 UTC
Permalink
local a = {
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
[6] = 6,
}
print(#a) -- print 6

‍

local a = {
[1] = 1,
[2] = 2,
[3] = 3,
[5] = 5,
[6] = 6,
}
print(#a) -- print 3

why?
‍
Alex
2014-08-21 03:38:27 UTC
Permalink
http://www.lua.org/manual/5.1/manual.html#2.5.5
The length of a table t is defined to be any integer index n such that
t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero.
For a regular array, with non-nil values from 1 to a given n, its length is
exactly that n, the index of its last value. If the array has "holes" (that
is, nil values between other non-nil values), then #t can be any of the
indices that directly precedes a nil value (that is, it may consider any
such nil value as the end of the array).
--
Sincerely,
Alex Parrill
Continue reading on narkive:
Loading...