Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua self references

Tags:

this

self

lua

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
like image 735
Snakybo Avatar asked Jun 22 '13 22:06

Snakybo


1 Answers

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

like image 155
Alar Avatar answered Nov 13 '22 09:11

Alar