问题描述
问题
当我使用 do
时,lua 关键字作为表的键会出现以下错误
> table.newKey = { do = 'test' }
stdin:1: unexpected symbol near 'do'
>
我需要使用 do
作为键。我该怎么办?
解决方法
使用以下语法:
t = { ['do'] = 'test' }
或 t['do']
获取或设置值。
SourceRow = 1
DestinationRow = 1
For SourceRow = 1 To LastSourceRow
Employee = SourceWorksheet.Cells(SourceRow,1).Value
Roles = Split(SourceWorksheet.Cells(SourceRow,2).Value,"/")
For i = LBound(Roles) To UBound(Roles)
DestinationWorksheet.Cells(DestinationRow,1).Value = Employee
DestinationWorksheet.Cells(DestinationRow,2).Value = Roles(i)
DestinationRow = DestinationRow + 1
Next i
Next SourceRow
是 sometable.somekey
的语法糖,
同样,sometable['somekey']
是 { somekey = somevalue }
的糖
可以在这个非常好的资源中找到这样的信息:
对于此类需求,还有另一种更通用的格式。在这种格式中,我们明确地将要初始化的索引写成一个表达式,放在方括号之间:
{ ['somekey'] = somevalue }
-- Programming in Lua: 3.6 – Table Constructors
,我需要使用 do 作为关键。我该怎么办?
阅读 Lua 5.4 参考手册并了解 t = { a = b}
或 t.a = b
之类的内容仅在 a
是有效的 Lua 标识符时才有效。
构造函数的一般语法是
tableconstructor ::= ‘{’ [fieldlist] ‘}’
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
fieldsep ::= ‘,’ | ‘;’
表单 name = exp
的字段等效于 ["name"] = exp
。
那么为什么这对 do
不起作用?
Lua 中的名称(也称为标识符)可以是任何拉丁语字符串 字母、阿拉伯-印度数字和下划线,不以 a 开头 数字而不是保留字。标识符用于命名 变量、表字段和标签。
以下关键字是保留的,不能用作名称:
and break do else elseif end
false for function goto if in
local nil not or repeat return
do
不是 name 所以你需要使用语法 field ::= ‘[’ exp ‘]’ ‘=’ exp
在您的示例中是 table.newKey = { ['do'] = 'test' }