Lua self references

Snakybo picture Snakybo · Jun 23, 2013 · Viewed 19.1k times · Source

How exacyly do you get variables within a program with self?

Like in Java you have:

private int a

public void sa(int a) { this.a = a}
public void ga() { return this.a }

VB has 'ME' and C# has 'this' etc.

But whats the Lua equivalent of this? Is this in the right direction?

local a

function sa(a)
    self.a = a
end

Answer

Alar picture Alar · Jun 23, 2013

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