2010-12-05 90 views
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." 

谢谢!

回答

2

首先,你所做的不是一个数组,而是一个字典。尝试:

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

否则table.insert可能是你在array_push

+0

table.insert是我一直在寻找的! – Chris 2010-12-06 20:54:16

1

想要什么这是几乎相同的有标准的Lua是这样的:

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

的table.key符号相当于表[“key”]表示法。 现在每个项目都有与数字键对应的值的描述,而子项目是与字符串键对应的值。

如果您确实想要与您的示例具有完全相同的语法,则必须使用metatables(__index和__newindex方法)。

2

以下索引 metamethod执行应该做的伎俩。

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

注意,你用字符串索引值混合数组索引值,我不认为你打算这样做。例如,您的第一行在关键字“1”下存储“Forest”,而第二行创建一个新的表格关键字“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) 
+0

谢谢你用一个明确的例子指出阵列构造错误:-),我再试一次。 – Chris 2010-12-06 20:53:40