如何将Lua关键字作为表的键?

4

问题

当我将Lua关键字do作为表的键时,会出现以下错误:

> table.newKey = { do = 'test' }
stdin:1: unexpected symbol near 'do'
>


我需要把 do 作为键名。我该怎么做?
3个回答

5

sometable.somekeysometable['somekey']的简写方式,

类似地,{ somekey = somevalue }{ ['somekey'] = somevalue }的简写方式。


这样的信息可以在这个非常好的资源中找到:

For such needs, there is another, more general, format. In this format, we explicitly write the index to be initialized as an expression, between square brackets:

opnames = {["+"] = "add", ["-"] = "sub",
           ["*"] = "mul", ["/"] = "div"}
-- Lua 编程:3.6 – 表构造器


4
请使用以下语法:
t = { ['do'] = 'test' }

使用t['key']来获取或设置值。


2
我需要使用do作为关键字,该怎么办?
请阅读Lua 5.4参考手册,并理解以下代码只有在a是有效的Lua标识符时才能正常工作:t = { a = b}t.a = b
详情请见:3.4.9 - Table constructors

The general syntax for constructors is

tableconstructor ::= ‘{’ [fieldlist] ‘}’

fieldlist ::= field {fieldsep field} [fieldsep]

field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp

fieldsep ::= ‘,’ | ‘;’

表单字段name = exp等同于["name"] = exp

那么为什么这对do不起作用呢?

3.1 - 词法约定

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.

The following keywords are reserved and cannot be used as names:

 and       break     do        else      elseif    end
 false     for       function  goto      if        in
 local     nil       not       or        repeat    return

do不是一个名称,所以你需要使用语法field ::= ‘[’ exp ‘]’ ‘=’ exp

在你的例子中,应该这样写:table.newKey = { ['do'] = 'test' }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接