给定一个表
t = {foo = "bar", bar = "foo"}
和一个变量
foo = "bar"
有什么区别
print(t.foo)
打印“bar”和
print(t[foo])
打印“foo”
最佳答案
t[expr]
是索引操作,其中t
是要索引的表,expr
是其值的表达式用作 key 。 t[foo]
因此计算结果为 t["bar"]
。键 bar
的值是字符串 foo
。因此 print(t[foo])
打印“foo”。
t.name
只是 t["name"]
的简写,其中 name 与 Lua 的标识符词法约定相匹配:
Names (also called identifiers) in Lua can be any string of Latin letters, Arabic-Indic digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels.
- Lua 5.4 Reference Manual
这意味着在索引时,name
不会被计算为表达式 name
,而是被计算为字符串文字 "name"
因此,t.foo
相当于 t["foo"]
,其计算结果为 bar
。
TL;DR:要使用值或其他表达式的变量对表进行索引,请使用t[expr]
。特别是,您必须使用 t[index]
来索引表的列表部分。如果 expr
是不符合标识符条件的字符串文字(例如:t["foo-bar"]),则还必须使用
)。要使用名称/标识符键对表进行索引,请使用t[expr]
t.name
。
关于indexing - Lua中t.foo和t[foo]的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73085668/