0

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!

moeux
  • 191
  • 15
  • This isn't valid syntax. It's not clear what you want `Maintable` and `subtable` to be, with `{` right after them. [Try it on tio.run](https://tio.run/##yylN/P8/Jz85MUfBNzEzryQxKSdVoZpLQaG4NAnBUVCoULBVMNABMytBTC6FWi4uhcSUlAggL600L7kkMz9PQ1MBSaceSA8SR1vBkEshNS@Fq/b/fwA) – aschepler Apr 01 '20 at 02:41
  • @aschepler, it is not, you're right. I corrected it. – moeux Apr 01 '20 at 03:15

1 Answers1

2

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()
DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38
  • Thank you for your answer! I was trying to use the table as class, since I normally program in Java. I was hoping I could use the subtable inside the class using a method, just like in Java. So I like the first solution better, why is the second one better? And Is self a thing in LUA? Like this. in Java? – moeux Apr 01 '20 at 12:28
  • `self` is not its own thing in Lua; it's really just another function argument, but calling a function in a table with `tab:func(foo)` is the same as calling it as `tab.func(tab, foo)` which makes it "look" like a method call. In most real-world cases, you don't even notice the difference. [Here](https://stackoverflow.com/questions/4911186/difference-between-and-in-lua)'s some more info on this :D – DarkWiiPlayer Apr 01 '20 at 13:29
  • I think I understood. Do I have to declare self as a function argument or is it being replace automatically with Maintable when I call the function as Maintable:addX()? – moeux Apr 01 '20 at 13:50
  • If you define the function as `function tab:func(foo)` it works the same way; it gets turned into `function tab.func(self, foo)` so you can use `self` inside the function. – DarkWiiPlayer Apr 01 '20 at 15:06