Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Can someone explain this?

Asked by 8 years ago

Please make your question title relevant to your question content. It should be a one-sentence summary in question form.

I'm not sure what and ... how

local t = {"1", "1", "1", "1"}
t[2] = nil 
t[4] = nil

print(#t) ---> 1

1 answer

Log in to vote
2
Answered by 8 years ago

See here; it says "Frequently, in Lua, we assume that an array ends just before its first nil element."

Now, "#t" is not guaranteed to work this way. The Lua Reference Manual states "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" (thanks to BlueTaslem for finding it); the full documentation is here. For instance, t={1,1,1} t[2]=nil print(#t) prints out 3 (though you should not rely on this behaviour, as it could just as easily print out 1).

If you need 'nil' values in a table, you have two options:

  • Declare nilValue = {} and use that instead of nil
  • Never use # on the table; use pairs to iterate over the table (notably, this will skip over nil values)
0
Another option is to `table.remove(t, 2)` instead -- this doesn't leave a gap BlueTaslem 18071 — 8y
0
"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" BlueTaslem 18071 — 8y
0
In your example #t is EITHER 1 or 3. ("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") [Lua reference 2.5.5] BlueTaslem 18071 — 8y
0
Thanks; good points. I've updated my answer. chess123mate 5873 — 8y
Ad

Answer this question