如何快速初始化Lua中的关联表?

49
在Lua中,您可以按照以下方式创建一个表格:
local t = { 1, 2, 3, 4, 5 }

然而,如果我想创建一个关联表,我必须按照以下方式完成:
local t = {}
t['foo'] = 1
t['bar'] = 2

以下内容出现错误:
local t = { 'foo' = 1, 'bar' = 2 }

有没有一种类似于我的第一个代码片段的方法来实现它?

3个回答

83
正确的写法应该是:要么这样写。
local t = { foo = 1, bar = 2}

或者,如果您表中的键不是合法标识符:

local t = { ["one key"] = 1, ["another key"] = 2}

请注意,这里有一个类似的答案,其中包含更多的解释,我发现更容易理解:https://dev59.com/cHHYa4cB1Zd3GeqPMoxz#16288476 - Seth

13
我相信如果您这样看,它会更好地运作并更易于理解。
local tablename = {["key"]="value",
                   ["key1"]="value",
                   ...}

使用以下格式查找结果:表名.键名=值

Tables as dictionaries

Tables can also be used to store information which is not indexed numerically, or sequentially, as with arrays. These storage types are sometimes called dictionaries, associative arrays, hashes, or mapping types. We'll use the term dictionary where an element pair has a key and a value. The key is used to set and retrieve a value associated with it. Note that just like arrays we can use the table[key] = value format to insert elements into the table. A key need not be a number, it can be a string, or for that matter, nearly any other Lua object (except for nil or 0/0). Let's construct a table with some key-value pairs in it:

> t = { apple="green", orange="orange", banana="yellow" }
> for k,v in pairs(t) do print(k,v) end
apple   green
orange  orange
banana  yellow

from : http://lua-users.org/wiki/TablesTutorial


2

要初始化一个具有字符串键和字符串值匹配的关联数组,您应该使用

local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};

local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接