I am having a problem fully understanding the lua syntax so while this answer may be simple perhaps some authorative references will help me and others further learn.
function blah()
and
function classname:blah()
I am having a problem fully understanding the lua syntax so while this answer may be simple perhaps some authorative references will help me and others further learn.
function blah()
and
function classname:blah()
Aubergine18's post covers the answer, but I'll explain from first principles to provide further clarification.
In Lua, functions are values, just like strings or numbers. This expression:
function() end
Creates a function value. You can assign this to a variable, just as you would any other value:
foo = function() end
Lua provides various short-cut syntaxes, also called "syntax sugar", for working with function values. The first is this:
function foo() end
This is exactly equivalent to:
foo = function() end
The other is:
function bar.foo() end
Which is exactly equivalent to:
bar.foo = function() end
In this example, bar
is a table, foo
is a key in that table, and the function value we created is the value assigned to that key.
Note that if you call foo:
bar.foo()
The function has no way of knowing that it was stored in the table bar
using the key foo
. If you want to treat that function as a method on the object bar
, you need to provide it access to bar
in some way. This is typically done by passing bar
as the first parameter. By convention in Lua this parameter is named self
:
function bar.foo(self) end
bar.foo(bar)
As a shortcut for this convention, Lua provides the following syntax sugar via the :
operator:
function bar:foo() end
bar:foo()
This is exactly equivalent to the previous code.
bar:foo()
given that bar
is silently passed into the method body, how do I call on bar
? Is it actually self
? –
Burny function bar:foo() end
is literally translated into function bar.foo(self) end
, so foo
has a first parameter named self
no matter what other parameters you do (or don't) give it. bar:foo()
is literally translated into bar.foo(bar)
, so inside of foo
, self
will contain bar
. –
Chamber When you call a function using colon notation, like this:
foo:bar()
Lua treats it like this behind the scenes:
foo.bar(foo)
If you define your function using dot notation, you'll have to manually specify the 'self' argument:
function foo.bar(self) ... end
However if you use colon notation, Lua will add an invisible 'self' parameter for you:
function foo:bar() ... end
Even though you don't see the self argument, it's there behind the scenes.
Basically colon notation is just a way to make your code look cleaner.
See also: Lua: colon notation, 'self' and function definition vs. call
© 2022 - 2024 — McMap. All rights reserved.