'this' link to the calling function in Lua

I am wondering how to get the link thisinside the Lua function. I'm used to having a link thisinside a function (like in JavaScript) that references the object that calls it.

For example, in JavaScript:

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

In this example, when called person.speak(), thisin the body of the function refers to person(which calls the function). How can I get a link to thisin a Lua function?

For example, the same object personin Lua:

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

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

+4
source share
2 answers

, .

self.

.., +

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

.

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

http://codepad.org/eXwWNKme irc

0

Source: https://habr.com/ru/post/1539677/


All Articles