How do i add a new key to a subtable, then reference it?

Post Reply
adamandkate
Posts: 4
Joined: Mon Nov 28, 2011 10:29 am

How do i add a new key to a subtable, then reference it?

Post by adamandkate »

Im having problems adding a key/value to a subtable. Then referencing it

This is an example of the table i want to create...

table {
1: table {
'Rome': table {
'Monster': 'Centurian'
'Monster': 'cesar'
}
'Paris': table {
'Monster': 'Napoleon'
}
}
}
and then i want to be able to reference the table and use if commandso n it
The code below is as far as ive got.
Code: [show] | [select all] lua
currentarea = gmcp.Room.Info.area
mob = matches[2]

table.insert (theworld,
     {[currentarea] = mob}
)
display(theworld)

-- the below doesnt fire at all. i think its because i dont want to use k,v but im not sure what.

table.foreach (theworld, 
      function (k, v)
       if k == "Rome" then
         echo("You are in Rome. RUN AWAY")
       end -- if 
       if k == "Paris" then
       parismonsters = table.concat (theworld.Hashan, ",")
       echo("You are in France. Monsters here are..." .. parismonsters)
       end -- if 
      end -- function
      )

User avatar
tsuujin
Posts: 695
Joined: Fri Feb 26, 2010 12:59 am
Location: California
Contact:

Re: How do i add a new key to a subtable, then reference it?

Post by tsuujin »

Code: [show] | [select all] lua
someTable = {
    "Rome" = {
        "Monsters" = {"Centurion", "cesar"}
    }, 
    "Paris" = {
        "Monsters" = {"Napolean"}
    }
}

someTable["Rome"]["Monsters"][1] // output: "Centurion"
You can also do it like this:
Code: [show] | [select all] lua
someTable = {}
someTable["Rome"] = {"Monsters" = {"Centurion", "cesar"}}
someTable["Paris"] = {}
someTable["Paris"]["Monsters"] = {}
table.insert(someTable["Paris"]["Monsters"], "Napolean")

Post Reply