1
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?

2 Answers 2

3

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Probably not exactly equivalent for global variables. Your example would get _G.obj twice, Lua will store the "self" object in a local variable when you do obj:printpos(other). So it's probably rather equivalent to do local obj = obj; obj.printpos(obj, other) end.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.