1

这可能是一个简单的问题,但我无法找到答案:如何在不覆盖(所有)旧值或必须重写它们的情况下向数组添加值?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."

谢谢!

4

3 回答 3

3

以下索引元方法实现应该可以解决问题。

local mt = {}

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

Array={"Forest","Beach","Home"} --places
setmetatable(Array, mt)
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."

请注意,您将数组索引值与字符串索引值混合在一起,我认为您不打算这样做。例如,您的第一行将“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
        A type of cutlery.
Forest
    1
        Trees
    2
        Flowers
    Trees
        A tree is a perennial woody plant

有了这种理解,您就可以在没有以下诡计的情况下解决您的问题。

Array = {
    Forest = {},
    Beach = {},
    Home = {}
}
Array["Forest"] = {
    Trees = "",
    Flowers = "",
}
Array["Forest"]["Trees"] = "A tree is a perennial woody plant"
Array["Restaurant"] = {
    Spoon = "A type of cutlery."
}

printtree(Array)

那么输出就是您可能期望的。

Restaurant
    Spoon
        A type of cutlery.
Beach
Home
Forest
    Flowers

    Trees
        A tree is a perennial woody plant

考虑到所有这些,以下内容完成了同样的事情,但在我的拙见中更加清晰。

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

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

Array.Forest.Trees = "A tree is a perennial woody plant"

Array.Restaurant = {}
Array.Restaurant.Spoon = "A type of cutlery."

printtree(Array)
于 2010-12-06T03:39:10.363 回答
2

首先,您制作的根本不是数组,而是字典。尝试:

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

否则table.insert可能是你想要的array_push

于 2010-12-05T19:44:00.950 回答
1

这在标准 Lua 中几乎相同,如下所示:

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

table.key 表示法等同于 table["key"] 表示法。现在每个项目在对应于数字键的值中都有它的描述,并且子项目作为对应于字符串键的值。

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

于 2010-12-05T20:02:18.823 回答