2

I am having trouble with my tables, I am making a text adventure in lua

local locxy = {}
      locxy[1] = {}
      locxy[1][1] = {}
      locxy[1][1]["locdesc"] =  "dungeon cell"
      locxy[1][1]["items"] = {"nothing"}
      locxy[1][1]["monsters"] = {monster1}

The [1][1] refers to x,y coordinates and using a move command I can successfully move into different rooms and receive the description of said room.

Items and monsters are nested tables since multiple items can be held there (each with their own properties).

The problem I am having is getting the items/monsters part to work. I have a separate table such as:

local monsters = {}
    monsters["rat"] = {}
    monsters["rat"]["Name"] = "a rat"
    monsters["rat"]["Health"] = 5
    monsters["rat"]["Attack"] = 1

I am using a table like this to create outlines for various enemy types. The monster1 is a variable I can insert into the location table to call upon one of these outlines, however I don't know how to reference it.

print("You are in ", locxy[x][y]["locdesc"]) -- this works
print("You can see a ", locxy[x][y]["monsters]["Name"],".") - does not work

So I would like to know how I can get that to work, I may need a different approach which is fine since I am learning. But I would also specifically like to know how to / if it possible to use a variable within a table entry that points to data in a separate table.

Thanks for any help that can be offered!

1 Answer 1

1

This line

locxy[x][y]["monsters]["Name"]

says

  1. look in the locxy table for the x field
  2. then look in the y field of that value
  3. look in the "monsters"` field of that value
  4. then look in the "Name" field of that value

The problem is that the table you get back from locxy[x][y]["monsters"] doesn't have a "Name" field. It has some number of entries in numerical indices.

locxy[x][y]["monsters][1]["Name"] will get you the name of the first monster in that table but you will need to loop over the monsters table to get all of them.

Style notes:

Instead of:

tab = {}
tab[1] = {}
tab[1][1] = {}

you can just use:

tab = {
    [1] = {
        {}
    }
}

and instead of:

monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "foo"

you can just use:

monsters = {
    rat = {
        Name = "foo"
    }
}

Or ["rat"] and ["Name"] if you want to be explicit in your keys.

Similarly instead of monsters["rat"]["Name"] you can use monsters.rat.Name.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the very quick and helpful response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.