Nested index in Lua: a['0'].b['0']?

Viewed 137

I'd like to implement some Lua data structure to achieve the following syntax:

  1. units -> returns a table of units.
  2. units[0] -> returns a number.
  3. units[0].properties -> returns a table of properties.
  4. units[0].properties[0] -> return the property of units[0], which is also a number.

The first 2 steps are trivial given a number indexed table. But can I achieve all 4 requirements at the same time?

I was thinking about creating units with customized __index metamethod. Is it the right direction?

1 Answers

One could set the metatable for all numbers (via debug.setmetatable) and use a __index metamethod to resolve the properties:

local properties_by_nums = {
  {42},
  {23},
}

local num_mt = {
  __index = function(n, i)
    if i == 'properties' then
      return properties_by_nums[n]
    end
    return nil
  end
}

debug.setmetatable(0, num_mt)

units = {1, 5}

print(type(units))                                          -- table
print(units[1], type(units[1]))                             -- 1, number
print(type(units[1].properties))                            -- table
print(units[1].properties[1], type(units[1].properties[1])) -- 42, table

The (probably cleaner) alternative would be to define your unit values as tables which behave like numbers. This can be achieved by implement the metamethods __add, __mul, etc.

Related