local t = { 1, 2, 3, 4, 5 }
然而,如果我想创建一个关联表,我必须按照以下方式完成:
local t = {}
t['foo'] = 1
t['bar'] = 2
以下内容出现错误:
local t = { 'foo' = 1, 'bar' = 2 }
有没有一种类似于我的第一个代码片段的方法来实现它?
local t = { 1, 2, 3, 4, 5 }
local t = {}
t['foo'] = 1
t['bar'] = 2
local t = { 'foo' = 1, 'bar' = 2 }
有没有一种类似于我的第一个代码片段的方法来实现它?
local t = { foo = 1, bar = 2}
或者,如果您表中的键不是合法标识符:
local t = { ["one key"] = 1, ["another key"] = 2}
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
要初始化一个具有字符串键和字符串值匹配的关联数组,您应该使用
local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};
但 不
local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};