lua - Calling Tables in any order

Viewed 37

My code is below for an example of what I'm trying to achieve.

When I compile a similar code structure to this I get the error "attempt to index a nil value global table2". I understand that if I move table2 above table 1, this error will clear itself. However, I want to be able to refer back to either table at any point in my script.

So if I'm at table11, I want to be able to reference table3 without needing to reorder my script.

Is there something I'm missing here on how to traverse tables?

table1 = {
    property1 = "string",
    property2 = table1[1],
    options = {
        optionTable[1],
        optionTable[2]
    },
    results = {
        table2,
        table3
    }
}

table2 = {
    property1 = "string",
    property2 = table1[2],
    options = {
        optionTable[3],
        optionTable[4]
    },
    results = {
        table1,
        table3
    }
}
1 Answers

You can't create circular references inside a table constructor, but you can create circular references by doing index assignments after you define the table.

table1 = {
  property1 = "string",
  options = {
    optionTable[1],
    optionTable[2]
  },
  results = {}
}
table1.property2 = table1[1]

table2 = {
  property1 = "string",
  property2 = table1[2],
  options = {
    optionTable[3],
    optionTable[4]
  },
  results = {
    table1,
  }
}
table1.results[1] = table2

table3 = {}
table1.results[2] = table3
table2.results[2] = table3

Note that stuff like table1[1] is nil here. I assume your actual code has that stuff filled in.

Related