在Lua中以0开始表的索引

时间:2013-10-31 07:00:21

标签: arrays lua lua-table

我想设置table-members的索引,但仍然命名它们。这可能吗?

local table = {
    ["cat"] = {
        ["fish"] = { stuff = "bla1", stuff2 = "bla" },
        ["mouse"] = { stuff = "bla2", stuff2 = "bla" },
        ["bird"] = { stuff = "bla3", stuff2 = "bla" },
    },
    ["dog"] = {
        ["fish"] = { stuff = "bla1", stuff2 = "bla" },
        ["mouse"] = { stuff = "bla2", stuff2 = "bla" },
        ["bird"] = { stuff = "bla3", stuff2 = "bla" },
    },
}

table["cat"][1]fish,但我希望table["cat"][0]fish,我该如何实现?

修改 我仍然希望能够fish访问table["cat"]["fish"]

EDIT2:

当我尝试这样做时,反之亦然? http://repl.it/MCu 我做错了什么?

2 个答案:

答案 0 :(得分:5)

您的表和嵌套在表中的表是纯哈希样式,没有数组样式。

数组样式的Lua表:

local t = {"cat", "dog", "fish"}

只是等效形式的语法糖:

local t = {[1] = "cat", [2] = "dog", [3] = "fish"}

您可以使用除nil以外的所有类型的键,确保您可以使用从0开始的整数键:

local t = {[0] = "cat", [1] = "dog", [2] = "fish"}

请注意,从0开始t不再是序列,因此您失去了仅用于序列的表函数的功能,例如#运算符,{{ 1}}等等。


要构建具有不同键的表,可以先创建值表,然后将不同的键绑定到同一个表中,如下所示:

ipairs

通过这种方式,local v = { ["fish"] = { stuff = "bla", stuff2 = "bla" }, ["mouse"] = { stuff = "bla", stuff2 = "bla" }, ["bird"] = { stuff = "bla", stuff2 = "bla" }, } local t = { ["cat"] = v, [0] = v, } print(t.cat.fish.stuff, t[0].fish.stuff) -- Output: bla bla t.cat可以访问同一个表格。

请注意,您可以使用语法糖形式t[0]代替table.cat.fish

答案 1 :(得分:4)

只是为了澄清table["cat"][1] 不是 a fish - 上面的表格示例根本没有使用表格的索引部分。要使用表的索引部分,键本身必须是整数。

修改上面的示例:

local animal = {
    cat = {
        fish = { stuff = "bla", stuff2 = "bla" },
        mouse = { stuff = "bla", stuff2 = "bla" },
        bird = { stuff = "bla", stuff2 = "bla" },
    },
    dog = {
        fish = { stuff = "bla", stuff2 = "bla" },
        mouse = { stuff = "bla", stuff2 = "bla" },
        bird = { stuff = "bla", stuff2 = "bla" },
    },
}

如果您希望animal.cat.fishanimal.cat[1]具有相同的值(相同的lua表),只需进行常规分配:

animal.cat[1] = animal.cat.fish
-- and likewise if you want index 0:
animal.cat[0] = animal.cat.fish

请注意,许多与表一起使用的标准lua函数从1开始计算。