38

在 Lua 中,您可以通过以下方式创建表:

local t = { 1, 2, 3, 4, 5 }

但是,我想创建一个关联表,我必须这样做:

local t = {}
t['foo'] = 1
t['bar'] = 2

以下给出了一个错误:

local t = { 'foo' = 1, 'bar' = 2 }

有没有办法类似于我的第一个代码片段?

4

3 回答 3

70

写这个的正确方法是

local t = { foo = 1, bar = 2}

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

local t = { ["one key"] = 1, ["another key"] = 2}
于 2009-02-04T21:08:33.093 回答
10

我相信如果你这样看,它会更好,更容易理解

local tablename = {["key"]="value",
                   ["key1"]="value",
                   ...}

找到结果:tablename.key=value

表作为字典

表也​​可用于存储未按数字或顺序索引的信息,如数组。这些存储类型有时称为字典、关联数组、散列或映射类型。我们将使用术语字典,其中元素对具有键和值。键用于设置和检索与其关联的值。请注意,就像数组一样,我们可以使用 table[key] = value 格式将元素插入表中。键不必是数字,它可以是字符串,或者几乎任何其他 Lua 对象(nil 或 0/0 除外)。让我们构建一个包含一些键值对的表:

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

来自: http: //lua-users.org/wiki/TablesTutorial

于 2011-12-06T09:24:23.760 回答
1

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

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

不是

local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};
于 2011-06-01T10:10:30.860 回答