Oliver Cooper
Oliver Cooper

Reputation: 845

lua - Access table item from within the table

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.

Upvotes: 4

Views: 2013

Answers (2)

Ilmo Euro
Ilmo Euro

Reputation: 5105

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

tbl.func(tbl)

and

tbl:func()

Upvotes: 4

Eric
Eric

Reputation: 97555

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

Parent:ChildFunction()

Upvotes: 7

Related Questions