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

Woo*_*kai 32 lua initialization lua-table

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

local t = { 1, 2, 3, 4, 5 }
Run Code Online (Sandbox Code Playgroud)

但是,我想创建一个关联表,我必须按以下方式执行:

local t = {}
t['foo'] = 1
t['bar'] = 2
Run Code Online (Sandbox Code Playgroud)

以下是错误:

local t = { 'foo' = 1, 'bar' = 2 }
Run Code Online (Sandbox Code Playgroud)

有没有办法像我的第一个代码片段那样做?

ben*_*din 59

写这个的正确方法是

local t = { foo = 1, bar = 2}
Run Code Online (Sandbox Code Playgroud)

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

local t = { ["one key"] = 1, ["another key"] = 2}
Run Code Online (Sandbox Code Playgroud)


Wes*_*ker 8

我相信如果你这样看它会更好,也可以理解

local tablename = {["key"]="value",
                   ["key1"]="value",
                   ...}
Run Code Online (Sandbox Code Playgroud)

使用以下命令查找结果:tablename.key = value

表格作为词典

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

t = {apple ="green",orange ="orange",banana ="yellow"}为k,v为成对(t)do print(k,v)end apple green orange orange orange banana yellow

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