Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua functions with colon

Tags:

lua

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()
like image 491
CodeCamper Avatar asked Aug 20 '15 23:08

CodeCamper


1 Answers

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.

like image 93
Mud Avatar answered Oct 07 '22 07:10

Mud