Here is an example that does not work, when calling the function self == nil:

function test() return { foo = "bar", say = function() print(self.foo) end } end 

And this is how it works, but I don’t like this record):

 function test() local result = {foo = "bar"} function result:say() print(self.foo) end return result end 

Check:

 local t = test() t:say() 

    1 answer 1

    The function must have self parameter:

     function test() return { foo = "bar", say = function(self) print(self.foo) end } end 

    Calls of the form t:say() actually always unfold in t.say(t) and if you want within the function say() have access to the fields of the table, you need to declare at least one parameter (with any name) in which you and this table will be transmitted. In Lua, the common name for such a parameter is self , but you can use any.

    If the function has several parameters, the table will always be passed as a "zero" parameter, i.e. the call t:say(x, y) will be translated to t.say(t, x, y) and when declaring the function you always you should expect the self parameter in the first place:

      say = function(self, x, y) print(self.foo) end 

    As for the syntax with a colon, this is so-called. syntactic sugar. In Lua, in fact, there are no classes, and they can only be emulated (to some extent) using tables. And so that this emulation looks similar to the use of classes, and such syntax was introduced.

    • I did not know that self can be explicitly passed as a parameter. Thank. - Beast Winterwolf
    • Fine. I propose to add this in response and clean the comments :) - D-side
    • Somehow it turns out that if the first argument of the function self, then it is not considered the first. For example, if after self you specify the second argument and then call the function, passing something to it, then this will be perceived as the second argument (and if you specify self as the second argument, then you can get confused). - Beast Winterwolf
    • self is an implicit (hidden) argument that is always automatically passed first. You cannot, at your will, pass it on to the second or not at all; you have no choice. And this is absolutely normal and exists in this form in many programming languages ​​where there are classes. In C ++ and Java, the keyword this used instead of self . - zed
    • Why so? Do not pass self I can! Just this was my problem, self was not transmitted. I learn lua after javascript and am well acquainted with this, but there it is actually transmitted automatically, but apparently there is no lua! - Beast Winterwolf