Home > Software design >  Understanding the difference between object.function(argument) and object:function(argument) in Lua
Understanding the difference between object.function(argument) and object:function(argument) in Lua

Time:03-11

obj ={x=30}

function obj:printpos()
  print(self.x)
end

other = {x=15}

obj.printpos(other)

The obj.printpos(other) gives expected output viz. 15. However the call obj:printpos(other) doesn't give expected output.It still prints 30. Why the call obj:printpos(other) is not taking other as its argument? Basically what is the difference between object.function(argument) and object:function(argument)? Is object:function(argument) same as object:function() i.e. whether argument is ignored?

CodePudding user response:

obj:printpos(other) is equivalent to obj.printpos(obj, other).

function obj:printpos() end is equivalent to function obj.printpos(self) end.

CodePudding user response:

From Lua 5.4 Reference Manual - §3.4.11 – Function Definitions (formatting mine):

The colon syntax is used to emulate methods, adding an implicit extra parameter self to the function. Thus, the statement

function t.a.b.c:f (params) body end

is syntactic sugar for

t.a.b.c.f = function (self, params) body end

From this, we can see the colon syntax implicitly adds the self parameter to the function scope.

Inversely, calling a function defined with the colon syntax using the dot syntax will cause the first argument passed to it to be assigned to the self parameter.

Thus, with

local thing = {}

function thing:func()
    print(self)
end

the calls

thing:func()
-- and
thing.func(thing)

have the same result of assigning thing to self, and

thing.func(other_thing)

will assign other_thing to self.

The problem with

thing:func(other_thing)

is that, as previously seen, thing is assigned to self. other_thing is assigned to no parameter, as no other parameters were defined.

  • Related