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屋!