'LUA: Having trouble understanding the difference between a.x and a[x]
As the Lua manual says, newbies to the language fall into the trap of thinking both a.x and a[x] are more alike than different. I am one of those newbies, ahaha.
Why does a.x give nil in this, but a[x] gives 10 and a.x gives nil?
a ={}
x = "y"
a[x] = 10
print(a[x]) --gives 10 for "y"
print(a.x) --gives nil for "x"
print(a.y) --give 10 for "y"
To be honest, I feel like I understand why the code above works, but I really want to know—conceptually— why:
invitems = {}
name = string.lower(name)
invitems[name] = "weapon"
print(invitems[name]) ----> gives weapon
print(invitems.name) ----> gives nil
print(invitems.string.lower(name)) ----> gives weapon
Solution 1:[1]
a[x] is the more fundamental indexing construct. a.x is syntactic sugar for a['x']. So in a[x], x is a variable name. In a.x, x is a literal string, which is unrelated to the variable x.
Solution 2:[2]
The syntax for table access in Lua is <table>[<expression>]. When you access a table using bracket notation, i.e., a[x], the expression x is evaluated first, and the value of x is used as a table index.
On the other hand, a.x is syntactic sugar for the table access a["x"]. Here, the string "x" is taken to be the table index.
Consider this interaction in the REPL:
> a = {}
> x = "y"
> a[x] = 10
> a.x
nil
> a[x]
10
> a["y"]
10
> a.y
10
With a[x] = 10, the x first evaluates to the value "y", and so the table accesses a["y"], storing the value 10 there. But before that the table was empty; the attempt to access a.x is equivalent to a["x"], and there is no value stored in a under the key "x", so nil is returned. But note that you could also access the value 10 which was stored by using a["y"], or a.y which is equivalent to a["y"].
Or consider this continuation of the above interaction:
> a[1] = 42
> z = 1
> a[z]
42
> a.z
nil
> a["z"]
nil
> a["z"] = "forty-two"
> a.z
forty-two
> a[z]
42
Now a[1] assigns the value 42 to the table field with the key 1. When z is given the value 1, we can access the new value in the table with a[z] because z evaluates to 1. But we can't access the value with a.z because there is no table field keyed to "z". After a["z"] = "forty-two" there is a value keyed to "z", and now it can be seen that a.z and a[z] are entirely different members of the table a.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | luther |
| Solution 2 |
