Functions

Declaring

Functions are declared with the 'def' keyword. They can only be declared outside of a statement; for example they cannot be inside of an if statement, while loop or another function.

def f( parameter1, anotherParameter, yetAnotherParameter )
    // do some work
end

Returning a value from a function is done using the 'return' keyword.

def f( a, b, c )
    return a + b*c
end

Unlike Ruby, the last value is not automatically returned. 'null' is always returned by default, unless you manually return a value.

If a function is declared inside of a class, then it becomes a method of that class. This is explained further in the classes section.

Calling

Calling a function is done by stating the function name, and then the values to pass in as parameters, surrounded by brackets. The values should be separated by a comma.

f( 59, x, 4.58 )

You can call a function anywhere in your program, even before it is declared.

Overloading

Quby supports function overloading, where the same function can be defined multiple times, but with different numbers of parameters.

def f()
end

def f( a )
end

def f( a, b, c )
end

Each of the above functions are entirely separate.

Optional parameters are not supported, but can be easily faked using function overloading.

Anonymous Functions

Anonymous functions, otherwise known as lambdas, like in Ruby and JavaScript, are supported.

Anonymous functions are functions that can be held by a variable, as they are objects in their own right. This means you can pass them around, pass them into functions, and call them later. They are called 'anonymous functions' because they do not have a defined name.

This makes them very similar to blocks, and in practice they are interchangable. However you are advised to use anonymous functions when you plan to store the function, and pass it around to other parts of your game.

To create an anonymous function you use the 'def' keyword, like defining a function, but you omit the identifier (the name of the function). For example:

// a doubling function
double = def( x )
    return x * 2
end

// creating a function, and passing it into a function call
foo(
        a, b,
        def(x, y) return x+y end
)

Anonymous functions are of the Function class, and so have all of it's methods. This includes the two 'call' methods, which you can use to the function:

getValue = def()
    return 42
end

// x is set to 42
x = getValue.call()

equation = def( a, b, c )
    return a + b*c
end

// y is set to '1 + 2*3', which is 7
y = equation.call([ 1, 2, 3 ])

The array is required in the second use of call, as it receives an array of values.

You can also create functions directly using the constructor:

double = def( x )
    return x * 2
end

double = new Function do |x|
    return x * 2
end

See also

Blocks - Methods - Function Class