Search code examples
arraysluaarray-push

Adding items to a multidimensional array without overwriting the old ones?


this may be a simple question, yet I haven't been able to find an answer to it: How do I add a value to an array without overwriting (all) old values, or having to rewrite them? Is there such a thing as array_push in LUA? And if so, does it work for multidimensional arrays as well?

Example:

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

If I'd like to add a description of a new thing in a new place, I can't do it using

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

because I'd have to declare all these things, as well as the old ones so I don't overwrite them. So I'm looking for something like:

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

Thanks!


Solution

  • First, what you're making is not an array at all, but a dictionary. Try:

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

    Otherwise table.insert may be what you want in array_push