Search code examples
lualua-table

Editing a subtable inside a maintable using a function inside the maintable


Is it possible to edit the contents of a table which is inside another table using a function?

local MainTable = {
  subtable = {
    x = 0,
    y = 0
 }, 

 addX = function() 
  subtable.x = subtable.x + 1
 end
}

I'm getting the error attempt to index ? (a nil value) Is it possible to achieve this? It works outside the table, I used:

print(MainTable.subtable.x+1)

How come it doesn't work inside the table? Does tables being objects play a role?

Thank you!


Solution

  • Lua tables aren't objects; just because you're declaring addX inside MainTable, it is not aware of anything else inseide MainTable.

    One solution would be:

    local MainTable
    MainTable = {
    ...
       addX = function()
          MainTable.subtable.x = MainTable.subtable.x + 1
       end
    }
    

    but a better way would be

    local MainTable = {
       subtable = {
          x = 0,
          y = 0
       }
    }
    
    function MainTable:addX() 
       self.subtable.x = self.subtable.x + 1
    end
    
    -- Use it as:
    MainTable:addX()