次のインデックスメタメソッドの実装でうまくいくはずです。
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」を格納し、2行目は連続した文字列値を保持するテーブル値を使用して新しいテーブルキー「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)
次は、上記の2つのコードスニペットの結果の出力です。
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)