Lua:使用字符串键创建隐式表 - 为什么要使用额外的括号?

kik*_*ito 13 lua

假设您要创建一个Lua表,并且其所有键都是有效的lua标识符.然后你可以使用key=value语法:

local niceTable = { I=1, like=1, this=1, syntax=1 }
Run Code Online (Sandbox Code Playgroud)

但是,如果您的字符串不是"可识别的",那么您必须使用以下['key']=value语法:

local operators = { ['*']="Why", ['+']="the", ['/']="brackets", ['?']='?' }
Run Code Online (Sandbox Code Playgroud)

我对此感到有点困惑.这些括号在那里做什么?他们的意思是什么?

Mud*_*Mud 21

索引表的常规语法是t[val].仅对于字符串键,Lua提供了一种替代语法,其中t.foo完全等同于t["foo"].这纯粹是一种语法上的便利,即所谓的"语法糖".它不会添加功能,它只会让您使用字符串作为命名字段的语法更简洁.

有很多字符串键这不适用于:

t["hello_world"] => t.hello_world  -- works
t["hello world"] => t.hello world  -- oops, space in the string
t["5 * 3"]       => t.5 * 3        -- oops
t['[10]']        => t.[10]         -- oops
Run Code Online (Sandbox Code Playgroud)

基本上它只有在字符串键是有效标识符时才有效.

同样,表是通过索引编写的[],在大多数情况下,您需要使用它们:

t = {
   -- [key]           = value
   [10]               = "ten", -- number key, string value
   ["print function"] = print, -- string key, function value
   ["sub table"]      = {},    -- string key, table value
   [print]            = 111,   -- function key, number value
   ["foo"]            = 123,   -- string key, number value
}
Run Code Online (Sandbox Code Playgroud)

只有当您使用的字符串键作为有效标识符(没有空格,仅包含单词字符,数字或下划线,并且不以数字开头)时,才能使用快捷语法.对于上表,那将只是'foo':

t = {
   -- [key]           = value
   [10]               = "ten", -- number key, string value
   ["print function"] = print, -- string key, function value
   ["sub table"]      = {},    -- string key, table value
   [print]            = 111,   -- function key, number value
   foo                = 123,   -- string key, number value
}
Run Code Online (Sandbox Code Playgroud)


Pup*_*ppy 19

它们将包含的字符串标识为结果表中的键.第一种形式,你可以认为是等于

local niceTable = {}
niceTable.I = 1;
niceTable.like = 1;
Run Code Online (Sandbox Code Playgroud)

第二种形式等于

local operators = {}
operators['*'] = "Why";
operators['+'] = "The";
Run Code Online (Sandbox Code Playgroud)

区别仅仅是语法糖,除非第一个使用标识符,所以它必须遵循标识符规则,例如不以数字和解释时间常量开头,第二个表单使用任何旧字符串,所以它例如,可以在运行时确定,以及不是合法标识符的字符串.但是,结果基本相同.对括号的需求很容易解释.

local var = 5;
local table = {
    var = 5;
};
-- table.var = 5;
Run Code Online (Sandbox Code Playgroud)

这里,var是标识符,而不是变量.

local table = {
    [var] = 5;
};
-- table[5] = 5;
Run Code Online (Sandbox Code Playgroud)

这里,var是变量,而不是标识符.