Question

I'm wondering how to get a this reference inside a Lua function. I'm used to having a this reference inside a function (like in JavaScript) that refers to the object that is calling it.

For example, in JavaScript:

var person = {
    'name' : 'Saucy Jack',
    'speak' : function() {
        console.log("Hi, my name is " + this.name);
    };
};

In that example, when person.speak() is called, this in the function body will reference person (which is calling the function). How can I get a reference to this in a Lua function?

For example, that same person object in Lua:

local person = {
    name = 'Saucy Jack',
    speak = function() 
        print("Hi, my name is " + self.name);
    end
};

From what I understand in Lua, self is used instead of this, but I can't get the above example to work.

Was it helpful?

Solution

First off, the semi-colons aren't required at all.

Next, you'd need to define the function outside of the table's body for implicit call using self.

And, string concatenation is done using .. and not +

local person = {
    name = 'Saucy Jack',
}
function person:speak()  -- or function person.speak(self)
    print("Hi, my name is "..self.name)
end

Here's a working codepad sample.

OTHER TIPS

local person = {
name = 'Saucy Jack',
speak = function(self) 
    print("Hi, my name is " .. self.name);
end
};
person:speak()    

http://codepad.org/eXwWNKme welcome to corona irc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top