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.

1local kRef = {
2    ["w"] = Enum.KeyCode.W,
3    ["a"] = Enum.KeyCode.A,
4    ["s"] = Enum.KeyCode.S,
5    ["d"] = Enum.KeyCode.D,
6    ["space"] = Enum.KeyCode.Space
7}
8print(#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.

1local kRef = {
2    Enum.KeyCode.W,
3    Enum.KeyCode.A,
4    Enum.KeyCode.S,
5    Enum.KeyCode.D,
6    Enum.KeyCode.Space
7}
8print(#kRef) --> 5
Ad
Log in to vote
0
Answered by 6 years ago
01local kRef = {
02    ["w"] = Enum.KeyCode.W,
03    ["a"] = Enum.KeyCode.A,
04    ["s"] = Enum.KeyCode.S,
05    ["d"] = Enum.KeyCode.D,
06    ["space"] = Enum.KeyCode.Space
07}
08 
09--If you want to print all the table's contents, use a loop:
10for i, v in pairs(kRef) do
11    print(v)
12end
0
I don't want the content, I want the size, and the size is 0. jaschutte 324 — 6y

Answer this question