Nanfeng

Notes on software development, code, and curious ideas

The Difference Between Dot and Colon Syntax in Lua

Lua’s colon syntax is shorthand for passing the receiver as the first argument, conventionally named self.

These definitions are equivalent:

1
2
3
4
5
6
7
function MainScene:onCreate()
print(self)
end

function MainScene.onCreate(self)
print(self)
end

These calls are also equivalent:

1
2
scene:onCreate()
MainScene.onCreate(scene)

The definition style and call style must agree. If a method is defined with a colon but called with a dot and no explicit receiver, self is missing. If a plain function is called with a colon, it receives one unexpected extra argument.

1
2
3
4
5
6
7
8
9
local Calculator = {}

function Calculator.add(a, b)
return a + b
end

function Calculator:addToTotal(value)
self.total = (self.total or 0) + value
end

Use dot syntax for functions that do not operate on a particular object, and colon syntax for instance methods. The colon does not create a class or copy a function; it only adds the receiver argument at the call or definition site.

When saving a method as a callback, preserve its receiver explicitly:

1
2
3
local callback = function(...)
return scene:onCreate(...)
end

Passing scene.onCreate by itself loses the object unless the callback API supplies it separately.

+