[SOLVED] Understanding the difference between object.function(argument) and object:function(argument) in Lua

Issue

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?

Solution

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

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

Answered By – shingo

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.