indexing - Lua中t.foo和t[foo]的区别

标签 indexing lua lua-table

给定一个表

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/

相关文章:

lua - _ENV 在 Windows 上的 Zerobrane Studio 中不工作

c++ - LuaPlus:如何让函数返回一个表?

python - 如何使用 Pandas 从 DataFrame 中拆分列

vb.net - 数据 GridView ...以编程方式设置选择行索引不会将 CurrentRow.Index 设置为相同?

mysql - 如何将带有 Doctrine 2 的 INDEX 添加到列而不使其成为主键?

android - 为 Android 编译 Lua lib - 成功,但奇怪的段错误

postgresql - 使用按位 AND 运算符对位串列的排除约束

lua - 具有较高概率给出低值的随机数生成器?

parsing - 将 CSV 文件转换为在 Lua 中定义键的表

lua - 检查数组是否包含特定值