Reputation: 571
> w={x=0, y=0, label = "console"}
> print(w[x])
nil
> print(w.x)
0
> print(w["x"])
0
>
Hi, I was wondering, why does print(w["x"]) give a 0, while print(w[x]) gives nil?
Upvotes: 0
Views: 251
Reputation: 28950
Because x and "x" are two different things.
x
is a nil-value and "x"
is a string.
print(w[x])
is equivalent to print(w[nil])
in your code.
w={x=0, y=0, label = "console"}
is syntantic sugar for
w={["x"]=0, ["y"]=0, ["label"] = "console"}
So {x=0}
actually stores 0
under the key "x"
.
From Lua Reference Manual 2.1 Values and Types:
The type table implements associative arrays, that is, arrays that can have as indices not only numbers, but any Lua value except nil and NaN. (Not a Number is a special value used to represent undefined or unrepresentable numerical results, such as 0/0.) Tables can be heterogeneous; that is, they can contain values of all types (except nil). Any key with value nil is not considered part of the table. Conversely, any key that is not part of a table has an associated value nil.
Upvotes: 2