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

Why does this array have 0 members?

Asked by
jaschutte 324 Moderation Voter
6 years ago

Why does this print 0? I really don't understand why.

local kRef = {
    ["w"] = Enum.KeyCode.W,
    ["a"] = Enum.KeyCode.A,
    ["s"] = Enum.KeyCode.S,
    ["d"] = Enum.KeyCode.D,
    ["space"] = Enum.KeyCode.Space
}
print(#kRef)

2 answers

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

When a dictionary is created, the keys inside of it do not have an order. Because of that, iterating through a dictionary may not give the values in the order you wrote. This is also why #keyRef printed 0, because of how the keys are stored. In order to fix this, you should remove the dictionary's indexes and make it a normal table.

local kRef = {
    Enum.KeyCode.W,
    Enum.KeyCode.A,
    Enum.KeyCode.S,
    Enum.KeyCode.D,
    Enum.KeyCode.Space
}
print(#kRef) --> 5

Ad
Log in to vote
0
Answered by 6 years ago
local kRef = {
    ["w"] = Enum.KeyCode.W,
    ["a"] = Enum.KeyCode.A,
    ["s"] = Enum.KeyCode.S,
    ["d"] = Enum.KeyCode.D,
    ["space"] = Enum.KeyCode.Space
}

--If you want to print all the table's contents, use a loop:
for i, v in pairs(kRef) do 
    print(v)
end
0
I don't want the content, I want the size, and the size is 0. jaschutte 324 — 6y

Answer this question