Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua - Access table item from within the table

Tags:

lua

I'm trying to create an object oriented implementation in Lua, for example:

Parent = {
  ChildVariable = "Hello",
  ChildFunction = function ()
     print(Parent.ChildVariable)
  end  
}

What I would like is rather than doing Parent.ChildVariable I can do ChildVariable instead; it is in the table so I thought must be some way to access it.

like image 922
Oliver Cooper Avatar asked Dec 21 '22 10:12

Oliver Cooper


2 Answers

Parent = {
  ChildVariable = "Hello",
  ChildFunction = function(self)
     print(self.ChildVariable)
  end  
}

Parent:ChildFunction()
like image 125
Eric Avatar answered Dec 23 '22 00:12

Eric


Lua has a special construct for that: the colon operator. The two following lines are equivalent:

tbl.func(tbl)

and

tbl:func()
like image 21
Ilmo Euro Avatar answered Dec 22 '22 23:12

Ilmo Euro