Lua self references

In lua, you dont have a specific class implementation but you can use a table to simulate it. To make things simpler, Lua gives you some "syntactic sugar":

To declare a class member you can use this full equivalent syntazes

  function table.member(self,p1,p2)
  end

or

  function table:member(p1,p2)
  end

or

  table.member = function(self,p1,p2)
  end

Now, comes the tricky part:

Invoking

table:member(1,2)

you get:

self=table,p1=1,p2=2

invoking

table.member(1,2)

you get:

self=1,p1=2,p2=nil

In other words, the : mimics a real class, while . resemble more to a static use. The nice thing is you can mix these 2 styles so, for example:

table.member(othertable,1,2)

gives

self=othertable,p1=1,p2=2

In this way you can "borrow" method from other classes implementing multiple inheritance


Keep in mind that a:b(...) and function a:b(...) ... end is just a syntactic sugar. self does not necessarily point to the "current object" because unlike in other programming languages, self is just a variable and can be assigned to anything. See the example below for a demonstration:

function table:member(p1, p2)
 print(self, p1, p2)
end

is just

table.member = function(self, p1, p2)
 print(self, p1, p2)
end

and

table:member(1, 2)

is just

table.member(table, 1, 2)

hence

function table:member(self, p1, p2)
 print(self, p1, p2)
end

table:member(1,2) --self=1 p1=2 p2=nil

because that's just

table.member = function(self, self, p1, p2)
 print(self, p1, p2)
end

table.member(table, 1, 2) --self=1 p1=2 p2=nil

Tags:

This

Self

Lua