Lua:使用字符串键创建隐式表 - 为什么要额外的括号? [英] Lua: implicit table creation with string keys - why the extra brackets?
问题描述
假设你要创建一个 Lua 表,并且它的所有键都是有效的 lua 标识符.然后你可以使用 key=value
语法:
Say that you want to create a Lua table, and all its keys are valid lua identifiers. Then you can use the key=value
syntax:
local niceTable = { I=1, like=1, this=1, syntax=1 }
但是,如果您的字符串不是可识别的",那么您必须使用 ['key']=value
语法:
If however your strings are not "identifiable", then you have to use the ['key']=value
syntax:
local operators = { ['*']="Why", ['+']="the", ['/']="brackets", ['?']='?' }
我对此有点困惑.那些括号在那里做什么?它们是什么意思?
I'm a bit baffled about this. What are those brackets doing there? What do they mean?
推荐答案
他们将包含的字符串标识为结果表中的键.第一种形式,你可以认为等于
They identify the contained string as a key in the resulting table. The first form, you could consider as equal to
local niceTable = {}
niceTable.I = 1;
niceTable.like = 1;
第二种形式等于
local operators = {}
operators['*'] = "Why";
operators['+'] = "The";
区别纯粹是语法糖,除了第一个使用标识符的地方,所以它必须遵循标识符规则,例如不以数字和解释时间常量开头,第二个形式使用任何旧字符串,因此它可以在运行时确定,例如,一个不是合法标识符的字符串.但是,结果基本相同.括号的必要性很容易解释.
The difference is purely syntactic sugar, except where the first one uses identifiers, so it has to follow the identifier rules, such as doesn't start with a number and interpret-time constant, and the second form uses any old string, so it can be determined at runtime, for example, and a string that's not a legal identifier. However, the result is fundamentally the same. The need for the brackets is easily explained.
local var = 5;
local table = {
var = 5;
};
-- table.var = 5;
这里,var 是标识符,而不是变量.
Here, var is the identifier, not the variable.
local table = {
[var] = 5;
};
-- table[5] = 5;
这里,var 是变量,而不是标识符.
Here, var is the variable, not the identifier.
这篇关于Lua:使用字符串键创建隐式表 - 为什么要额外的括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!