Retrieve an attribute from the same table in LUA

165 Views Asked by At

I would like to know if it was possible to retrieve the attribute of a table in the same array. For example here I want to retrieve the "list.index" attribute of my array, how to do?

{
category_title = "Weapon",
description = nil,
type = "list",
list = {items = {"Give", "Remove"}, index = 1},
style = {},
action = {
   onSelected = function()
      if list.index == 1 then
         -- it's 1
      else
         -- it's 2
      end
   end
},
2

There are 2 best solutions below

0
lhf On BEST ANSWER

It's not possible to use an entry in another entry when the table is being created.

But since you're defining a function, you can do this:

   onSelected = function(self)
      if self.list.index == 1 then
         -- it's 1
      else
         -- it's 2
      end
   end

Just make sure you call onSelected with the table as an argument.

0
Luatic On

Alternatively, you may set the function after constructing the table in order to be able to access the table as an upvalue (as opposed to leveraging table constructors):

local self = {
   categoryTitle = "Weapon",
   description = nil,
   type = "list",
   list = {items = {"Give", "Remove"}, index = 1},
   style = {},
   action = {}
}
function self.action.onSelected()
   if self.list.index == 1 then
      -- it's 1
   else
      -- it's 2
   end
end

That way, you get self as an upvalue and don't need to pass it as an argument.