micha wrote:The self-notation is so-called syntactic sugar. That means it's just a short way of writing something, which is a bit longer if written out.
self isn't the syntactic sugar, the colon (:) operator is the syntactic sugar, which causes self to represent...itself. Here's a more robust example:
Code: Select all
local Player = {}
Player.__index = Player
function Player:new(name)
return setmetatable({
name = name
}, self)
end
--- Dot notation declaration
-- I can call the first parameter anything, because I am explicitly declaring it
function Player.foo1(player, bar)
print(player.name, bar)
end
--- Colon notation declaration
-- I can only refer to fields of the current object using self, because it is implied to
-- be the name of the first parameter
function Player:foo2(bar)
print(self.name, bar)
end
local p = Player:new("Michael")
Player.foo1(p, "Dot notation foo1")
-- prints "Michael Dot notation foo1"
p:foo1("Colon notation foo1")
--prints "Michael Colon notation foo1"
Player.foo2(p, "Dot notation foo2")
-- prints "Michael Dot notation foo2"
p:foo2("Colon notation foo2")
-- prints "Michael Colon notation foo2"
When
declaring a function, the colon (:) forces you to use self to refer back to the calling object, but otherwise performs essentially the same as if you declared the first parameter yourself using the dot (.) notation.
When
invoking the functions, the first two are the same call, as well as the second two (albeit with different bar parameters). All the colon (:) notation does is transplant the object you are using to call the function into the first (hidden) parameter, called self.
You can also see that regardless of how I declared the functions, when I invoke them, I can use either notation to achieve the same result. I would bet, however, that the more Lua-like way would be to use the colon (:) notation when using tables as objects, and the dot (.) notation when using tables as namespaces.
(You probably knew this, but it might be a bit confusing for someone new to Lua's object orientation.)