在 Lua 中使用带有句点的表键
在 Lua 中,为一个表分配一个指定的键可能会像这样:
a = { x = 4 }
...或者可能像...
a = { ['x'] = 4 }
很简单。但是,如果我在密钥中引入句点(如在域名中),则似乎不起作用。以下所有操作都会失败:
a = { "a.b.c" = 4 }
a = { a.b.c = 4 }
a = { ['a.b.c'] = 4 }
a = { ["a.b.c"] = 4 }
a = { [a.b.c] = 4 }
所有这些都会返回相同的错误:
$ ./script.lua
/usr/bin/lua: ./script.lua:49: `}' expected near `='
我在这里缺少什么?其中几个示例看起来非常简单并且应该有效(而其他示例则有明显的问题)。
In Lua, assigning a table with a specified key might go like this:
a = { x = 4 }
...or perhaps like...
a = { ['x'] = 4 }
Easy enough. However, if I introduce periods into the key (as in a domain name) nothing seems to work. All of the following fail:
a = { "a.b.c" = 4 }
a = { a.b.c = 4 }
a = { ['a.b.c'] = 4 }
a = { ["a.b.c"] = 4 }
a = { [a.b.c] = 4 }
All of these return the same error:
$ ./script.lua
/usr/bin/lua: ./script.lua:49: `}' expected near `='
What am I missing here? Several of the examples seem quite straight-forward and should work (while others have apparent problems).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 lua 中,表元素可以是名称或表达式。引用语言参考,“Lua 中的名称(也称为标识符)可以是任何字母、数字和下划线组成的字符串,不能以数字开头。”,在此上下文中,其他所有内容都被解释为标识符。因此,
abc
作为表索引被视为表达式,对其进行求值以获得实际的表索引。这可以工作,但毫无用处:另请注意,
foo.abc
等于foo['a']['b']['c']
并且不是foo['abc']
。In lua table element may be either a Name or an Expression. Citing language reference, "Names (also called identifiers) in Lua can be any string of letters, digits, and underscores, not beginning with a digit.", and everything else is interpreted as an identifier in this context. Therefore,
a.b.c
as a table index is treated as expression, which is evaluated to get the actual table index. This would work, but would be useless:Also note, that
foo.a.b.c
is equal tofoo['a']['b']['c']
and not tofoo['a.b.c']
.这两个都是有效的。
此可能有效,具体取决于所使用的确切标识符。例如
将是有效的。
如果您的解释器告诉您它们无效,那么您要么做错了什么,要么解释器中存在错误。然而,其他的则无效。
These two are all valid.
This could be valid, depending on the exact identifiers used. For example
would be valid.
If your interpreter is telling you they are not valid, then you've either done something else wrong, or there's a bug in the interpreter. The others however would not be valid.
你的脚本还有其他问题吗?
Is there something else wrong in your script?