2

我想设置表成员的索引,但仍然命名它们。那可能吗?

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"].

编辑2:

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

4

2 回答 2

4

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

数组样式的 Lua 表:

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

只是等效形式的语法糖:

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

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

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

请注意,从0made开始t不再是序列,因此您失去了仅在序列上使用的表函数的功能,例如#运算符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.catt[0]访问同一张表了。

请注意,您可以使用语法糖形式table.cat.fish而不是table["cat"]["fish"]

于 2013-10-31T07:12:45.997 回答
4

只是为了澄清table["cat"][1] 不是- 你上面的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 开始计数。

于 2013-10-31T07:39:17.560 回答