微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 lua 关键字作为表键?

如何解决如何使用 lua 关键字作为表键?

问题

当我使用 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 标识符时才有效。

3.4.9 - Table constructors

构造函数的一般语法是

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

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

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

fieldsep ::= ‘,’ | ‘;’

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

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

3.1 - Lexical Conventsions

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' }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。