如何将项添加到多维数组中而不覆盖旧的项?

这可能是一个简单的问题,但我还没有找到答案:

如何将值添加到数组中而不覆盖(所有)旧值,或者不必重写它们?LUA 中是否有 array_push 这样的东西?如果有的话,它是否也适用于多维数组?

示例:

Array={"Forest","Beach","Home"} --places
Array["Forest"] = {"Trees","Flowers"} --things you find there
Array["Forest"]["Trees"] = "A tree is a perennial woody plant" --description

如果我想在新地方添加新事物的描述,我无法使用

Array["Restaurant"]["Spoon"] = "A type of cutlery."

因为我必须声明所有这些事物,以及旧的事物,以便我不会覆盖它们。因此,我正在寻找类似于:

array_push(Array, "Restaurant")
array_push(Array["Restaurant"],"Spoon")
Array["Restaurant"]["Spoon"] = "A type of cutlery."

谢谢!

原文链接 https://stackoverflow.com/questions/4358811

点赞
stackoverflow用户282536
stackoverflow用户282536

首先,你所创建的不是数组,而是字典。尝试使用以下代码:

T = { Forest = { } , Beach = { } , Home = { } }
T.Forest.Spoon = "A type of cutlery"

否则,在 array_push 中你可能需要使用 table.insert

2010-12-05 19:44:00
stackoverflow用户513763
stackoverflow用户513763

这在标准 Lua 中几乎完全一样,如下所示:

Array.Restaurant={}
Array.Restaurant.Spoon={}
Array.Restaurant.Spoon[1]="一种餐具。"

table.key 记号相当于 table["key"] 记号。 现在每个项目的描述都在对应于数字键的值中,子项目作为对应于字符串键的值。

如果你真的想要与你的示例完全相同的语法,你就必须使用元表(__index 和 __newindex 方法)。

2010-12-05 20:02:18
stackoverflow用户1491
stackoverflow用户1491

下面的 index 元方法实现应该可以解决问题。

local mt = {}

mt.__index = function(t, k)
        local v = {}
        setmetatable(v, mt)
        rawset(t, k, v)
        return v
end

Array={"Forest","Beach","Home"} -- 地方
setmetatable(Array, mt)
Array["Forest"] = {"Trees","Flowers"} -- 那里能找到的物品
Array["Forest"]["Trees"] = "一棵树是一种多年生木质植物" -- 描述
Array["Restaurant"]["Spoon"] = "一种餐具。"

请注意,您在混合数组索引值和字符串索引值,我认为您并不打算这样做。例如,您的第一行将“Forest”存储在键“1”下,而第二行创建了一个新的表键“Forest”,其表值包含顺序字符串值。以下代码打印生成的结构以证明我的意思。

local function printtree(node, depth)
    local depth = depth or 0
    if "table" == type(node) then
        for k, v in pairs(node) do
            print(string.rep('\t', depth)..k)
            printtree(v, depth + 1)
        end
    else
        print(string.rep('\t', depth)..node)
    end
end

printtree(Array)

接下来是上述两个代码片段的生成输出。

1
    Forest
2
    Beach
3
    Home
Restaurant
    Spoon
        一种餐具。
Forest
    1
        Trees
    2
        Flowers
    Trees
        一棵树是一种多年生木质植物

有了这个理解,您可以按照以下方式解决问题,而无需使用诸如技巧之类的东西。

Array = {
    Forest = {},
    Beach = {},
    Home = {}
}
Array["Forest"] = {
    Trees = "",
    Flowers = "",
}
Array["Forest"]["Trees"] = "一棵树是一种多年生木质植物"
Array["Restaurant"] = {
    Spoon = "一种餐具。"
}

printtree(Array)

输出结果是您可能预期的。

Restaurant
    Spoon
        一种餐具。
Beach
Home
Forest
    Flowers

    Trees
        一棵树是一种多年生木质植物

在此基础上,以下代码可以实现相同的效果,但在我的看法中更清晰。

Array.Forest = {}
Array.Beach = {}
Array.Home = {}

Array.Forest.Trees = ""
Array.Forest.Flowers = ""

Array.Forest.Trees = "一棵树是一种多年生木质植物"

Array.Restaurant = {}
Array.Restaurant.Spoon = "一种餐具。"

printtree(Array)
2010-12-06 03:39:10