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

Why is this array saying there is nothing inside when there is?

Asked by
synkrio 281 Moderation Voter
4 years ago
            healList[v.UserId] = healBeam
            for i,v in pairs(healList)do
                print(v.Name) -- prints UserId of player
            end
            print(#healList) -- prints 0

The array has something inside as it printed out the UserId of the player, yet it says there is nothing in the array. Can anyone help me understand why this is happening?

1 answer

Log in to vote
0
Answered by
compUcomp 417 Moderation Voter
4 years ago

The length operator doesn't actually count the number of elements in an array. It finds the largest consecutive index starting at 1. This means that:

local array = {}
array[2] = 2
array[3] = 3
print(#array) -- will print 0, since array[1] is nil

You are using UserIds, which of course would not be consecutive. To properly count the elements in your array:

local count = 0
for _,_ in pairs(healList) do
    count = count + 1
end
print(count) -- correct number of keys
Ad

Answer this question