Functions
In the checkpoint hunt script from the previous chapter, the code that reads the player’s position appeared twice — once for the base point and once inside the loop. If we wanted to add a third use, we’d have to copy the same lines again. And if the pattern were more complex — say, loading a model and waiting for it — duplication would quickly get out of hand.
A function wraps a piece of code into a reusable block with its own name. You write the code once, then call the function wherever you need it.
Syntax
function <name>(<parameters>) <body>endHere’s a simple function that loads a model and waits until it’s ready:
function loadModel(modelId: int) request_model modelId while not has_model_loaded modelId wait 0 endendloadModel is the function’s name. modelId is a parameter — a value the caller provides. Inside the body, modelId works just like a local variable.
To call the function, use its name followed by parentheses with the argument:
loadModel(415) // load CheetahloadModel(522) // load NRG-500Each call runs the full request-and-wait pattern. The request-wait loop that took 4 lines now takes 1 line at each call site.
Parameters
A function can accept zero or more parameters. Each parameter has a name and a type, separated by a colon:
function setTime(hour: int, minute: int) set_time_of_day hour minuteend
setTime(12, 30)If a function takes no parameters, use empty parentheses:
function resetWeather() release_weatherend
resetWeather()Placing Functions in a Script
Place functions where normal code flow can’t reach them. A common pattern is to put all functions at the end of the script, e.g. after terminate_this_script or other functions:
{$CLEO .cs}// main code hereterminate_this_script
// functions herefunction foo() ...endfunction bar() ...end