Search code examples
luathisself

Lua self references


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

Solution

  • It is somewhat how you are saying it, but the OOP approach is a little bit different. The following is actually the method.

    local t = {
        a
    }
    t.__index = t
    
    function t:sa(x)
        self.a = x
    end
    

    And then, to call the function:

    t:sa(21)
    

    or

    t.sa( t, "some string this time?" )