带更改变量的 Lua 表 - Mental Block
我一直认为将 k
的值从 "x"
更改为 20
会消除 "x"
。那么为什么在这个例子中我们能够返回并引用 "x"
呢?
a = {}
k = "x"
a[k] = 10
print(a[k]) ---> Returns 10
print(a["x"]) ---> Returns 10
a[20] = "great"
k = 20
print(a[k]) ---> "great"
a["x"] = a["x"] + 1
print(a["x"]) --> 11
为什么最后一个打印命令有效并返回11
?我以为我们设置了k
= 20
。为什么“x”
也在图片中?
I always assumed that changing the value of k
from "x"
to 20
would eliminate "x"
. So why then in this example are we able to go back and reference "x"
?
a = {}
k = "x"
a[k] = 10
print(a[k]) ---> Returns 10
print(a["x"]) ---> Returns 10
a[20] = "great"
k = 20
print(a[k]) ---> "great"
a["x"] = a["x"] + 1
print(a["x"]) --> 11
Why does that last print command work, and return 11
? I thought we set k
= 20
. Why is "x"
even in the picture?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lua 将表称为其他编程语言中的字典或哈希,表是存储一对键和值的数据结构,表中不能有两个相同的键,但不同的键可以具有相同的值。所以基本上你在第2行中所做的就是给你的变量“k”值“x”,在第3行你说表“a”将有一个值为10的条目,该条目由键“x”而不是变量引用“k”,变量“k”是一个地址而不是一个值。
我希望我能有所帮助。
Lua calls table what others programming languages call dictionary or hash, a table is a data structure that stores a pairs of key and value, we can not have two identical keys in a table, but we can have same values for diferent keys. So basicly what you are doing in line 2 is giving your variable "k" value "x", on line 3 you are saying that the table "a" will have an entry with value 10 which is referenced by key "x" not variable "k", variable "k" is a anddress not a value.
I hope I helped somehow.