A function is a block of organized, reusable code that is used to perform some actions. Function can accept parameters and can return values.
To call a function without parameters and not returning anything, type its name and a pair of brackets:
ClearScreen()To call a function with parameters, but not returning anything, type its name and parameters separated by commas inside a pair of brackets:
DrawText(10, 10, "Hello World")To call a function returning a value, call it as above, but use the return value in expressions or for assignment:
a = sin ( 3 ) b = cos ( PI () * 2 )
To write a function without parameters and not returning anything, type keyword FUNCTION, function name and a pair of brackets. Then type some code, and finish it with END FUNCTION keywords:
function ClearAndDraw() ClearScreen() DrawRectangle(100, 100, 300, 200) end functionTo write a function with parameters, but not returning anything, type keyword FUNCTION, function name and type its parameters separated by commas inside a pair of brackets. Then type some code, and finish it with END FUNCTION keywords. Function parameters can be used as local variables inside the function:
function ClearAndDraw(x1, y1, x2, y2) ClearScreen() DrawRectangle(x1, y1, x2, y2) end functionTo write a function returning a value, write it as above and assign the return value to a local variable named the same as function name:
function ClearDrawAndGetArea(x1, y1, x2, y2) ClearScreen() DrawRectangle(x1, y1, x2, y2) ClearDrawAndGetArea = abs(x2 - x1) * abs(y2 - y1) end function area = ClearDrawAndGetArea(100, 100, 300, 200) ' area is 20000
' This function will not be used, since it is overloaded later function ClearAndDraw(x1, y1, x2, y2) ClearScreen() DrawRectangle(x1, y1, x2, y2) end function ' This function will be used, since it is a correct overload function ClearAndDraw(x1, y1, x2, y2) ClearScreen() DrawImageRectangle(x1, y1, x2, y2, $Image) end function ' This an example of incorrect overload. ' Number of parameters is different and ' an error will be reported function ClearAndDraw(x1, y1, x2, y2, x3, y3, x4, y4) ClearScreen() DrawImageQuad(x1, y1, x2, y2, x3, y3, x4, y4, $Image) end functionIt is common to overload event functions:
function OnKeyboard(char) ClearScreen() DrawText(100, 100, char) end function
See also: