Alex Rivera | Logout

How to reference lua table member from table member?

Asked 2012-08-08T00:32:26.580
8

i have a table in lua:

enUS = {
   LOCALE_STHOUSANDS = ",",  --Thousands separator e.g. comma

   patNumber = "%d+["..LOCALE_STHOUSANDS.."%d]*", --regex to find a number

   ["PreScanPatterns"] = {
      ["^("..patNumber..") Armor$"] = "ARMOR",
   }
}

So you see there is a whole chain of self-references in this table:

  • LOCAL_STHOUSANDS
    • patNumber
      • ["^("..patNumber..") Armor$"]

How can i perform self-referencing in an lua table?


What i don't want to do is have to hard-replace the values; there are hundreds of references:

enUS = {
   LOCALE_STHOUSANDS = ",",  --Thousands separator e.g. comma

   patNumber = "%d+[,%d]*", --regex to find a number

   ["PreScanPatterns"] = {
      ["^(%d+[,%d]*) Armor$"] = "ARMOR",
   }
}
lua
Edit
Report

1 Answer

10

How can i perform self-referencing in an lua table?

You don't.

Lua is not C. Until the table is constructed, none of the table entries exist. Because the table itself doesn't exist yet. Therefore, you can't have one entry in a table constructor reference another entry in a table that doesn't exist.

If you want to cut down on repeated typing, then you should use local variables and do/end blocks:

do
  local temp_thousands_separator = ","
  local temp_number_pattern = "%d+["..LOCALE_STHOUSANDS.."%d]*"

  enUS = {
   LOCALE_STHOUSANDS = temp_thousands_separator,  --Thousands separator e.g. comma

   patNumber = "%d+["..temp_thousands_separator.."%d]*", --regex to find a number

   ["PreScanPatterns"] = {
      ["^("..temp_number_pattern..") Armor$"] = "ARMOR",
   }
  }
end

The do/end block is there so that the temporary variables don't exist outside of the table creation code.

Alternatively, you can do the construction in stages:

  enUS = {}
  enUS.LOCALE_STHOUSANDS = ",",  --Thousands separator e.g. comma

  enUS.patNumber = "%d+["..enUS.LOCALE_STHOUSANDS.."%d]*", --regex to find a number

  enUS["PreScanPatterns"] = {
      ["^("..enUS.patNumber..") Armor$"] = "ARMOR",
   }
answered 2012-08-08T00:43:13.080

Your Answer