Functions

A function is a sequence of program instructions that performs a specific task, packaged as a unit. It is the main mechanism for abstraction of statements and expressions in Lua.

Example
-- Use this function to perform your initial setup function setup print("Hello, World!") end

Use
Functions can both carry out a specific task (what is sometimes called  procedure  or  subroutine  in other languages) or compute and return values.

Default Declaration
function name(param1, param2, ...) -- Code goes here end In this way, you start declaring the sequence with the function keyword, followed by the function name, followed by the parameters in round brackets, followed by the code until the matching end.

Assigning a nameless function to a variable
name = function (param1, param2, ...) -- Code goes here end

Calling a function
To call the function, write down the name of the function, followed by brackets, where you include your parameter print(8 * 9, 8 / 9) a = math.sin(8) + math.sin(9) print(os.date)

Leaving out parentheses
If the function has one single argument and this argument is either a literal string or a table constructor, then the parentheses are optional. print "Hello, World!" f{x = 5, y = 6} math.sin 9

Special Functions
In Codea, special functions are named setup, draw, touched, collide and sizeChanged.

setup-Function
function setup ... end The Setup-Function is once called automatically when your app loaded. It is used to initialise all the variables, which need to have a value. Images, Meshes and other classes, which initialisation time would cost much have to be initialised here.

Note! Empty tables should be initialised outside of any function. -- Allowed t = {} t.k = {} function setup t.k.n = 5 end function draw t.k.n = t.k.n + 5 end -- Not Suggested function setup t = {} t.k = {} t.k.n = 5 end function draw t.k.n = t.k.n + 5 end This helps to structure the code better.

draw-Function
function draw ... end The draw function is per default called 60 times every second. This may however vary from iPad processing speed to code structure. It is used for drawing and displaying contents. The main goal here is to avoid low frame rates.

touched-Function
function touched ( touch ) ... end The touch function includes the touch table (as the first argument) and is called every time, when the touch state changes (buttons from Codea and the input/output panel are ignored). It is your main way to control the input of touches.