I’m not sure if this is causing the problem because it isn’t clear “what is not working” but one thing that confused me starting out with Lua is that while a table acts like an array sometimes, it acts like a dictionary other times and then you can’t treat it like an array.
What does that mean? Basically, doing this #AliveTable
to a table acting like an array will return the correct count of elements. But doing the same thing to a table acting like a dictionary will not!
For a dictionary you need something like this
function getTableLength(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
return count
end
Example of “table as array”:
{ "this", "is", "array" }`
Example of table as dictionary:
{ ["this"] = 1, ["is"] = 2, ["dictionary"] = 3 }
The behavior of the #
operator then makes sense when reading the docs… see here
2.5.5 – The Length Operator
The length operator is denoted by the unary operator #
. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
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).
Dictionaries have “holes”. Arrays do not.
If you use
for i = 1, getTableLength(AliveTable) do
...
end
It may work as you’re expecting.