Ludicrous Software

Object-Oriented Function Calls in Corona

If you’re coming to Lua from another programming language, one of the things that will look unusual when you see sample code is manner in which many built-in functions are called.

For example, if you want to insert a value into a table, you’ll often see the code written like this:

1
2
local myTable = {"a", "b", "d"}
table.insert(myTable, 3, "c")

This is different from, say, ActionScript, where the equivalent code would look like this:

1
2
var myArray:Array = ["a", "b", "d"];
myArray.splice(2, 0, "c");

Ignoring the differing syntax between insert and splice for the moment, notice that the splice method is called directly on myArray, which determines the scope. In Lua, the insert method is akin to a static method of the table module, and the first argument is the table that will have the value inserted.

If you want your Lua to look more like ActionScript (or JavaScript, etc.), then all you need to do is make one simple change to your code:

1
2
local myTable = {"a", "b", "d"}
myTable:insert(3, "c")

Basically, using the colon before the function call is for convenience: it lets you skip having to pass the object as the first argument. When you’re writing functions in your own code, the colon serves the same purpose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
local myRect = display.newRect(0, 0, 100, 100)

function myRect.rotateTo(self, angle)
  self.rotation = angle
end

-- These two calls are functionally (ha ha!) equivalent
-- Pass myRect explicitly
myRect.rotateTo(myRect, 45)
-- myRect is the implicit first argument
myRect:rotateTo(45)

function myRect:fadeTo(newAlpha)
  -- 'self' isn't declared, but it's the implicit first parameter because of
  -- the colon in the function declaration
  self.alpha = newAlpha
end

-- again, these do the same thing
myRect:fadeTo(0.5)
myRect.fadeTo(myRect, 0.5)