Functions or procedures are one of the building blocks of Torque scripts. Many elements of game logic involve writing callbacks, functions that are called when a specific event happens in the game.
Functions are defined similarly to PHP:
Things you should know about functions in TorqueScript:
- If you define a function with the same name as an existing function, the current definition is overwritten. So, there's no function overloading like in C++.
- If you call a function with more parameters than the function takes, nothing happens - those parameters just aren't accessible.
- If you call a function with fewer parameters than it accepts, the remaining parameters are passed an empty string.
- Recursion is supported.
Functions with namespaces
Many useful callbacks happen on objects, which belong to namespaces. To define a function within a particular namespace, use ::, as in C++. For example:
defines a callback onCollision in the PlayerData namespace. Note that object classes and also object names are namespaces in TS, and that namespaces cannot be nested.
Useful function tools
Torque defines some useful functions that help you work with functions.
isDefined will check if the name you're given is defined as a function. Similarly, isMethod will check whether an object's namespace includes the particular named function you specify. For example:
call will call a function with the name and parameters you give it.
As of version 3.7, TorqueScript functions can be anonymous. An anonymous function is treated as an expression, so you can assign it to a variable. Its value is an autongenerated name you can use to call it. For example:
Note that, as in the above examples, you must put a semicolon after anonymous function declarations, even though you don't have to do this with regular functions. Anonymous functions are useful when you would otherwise define a one-time-use function to use, for example, in a schedule:
In TS, anonymous functions do not capture anything from the scope they are defined in. So,
will echo "" because %value is undefined inside the anonymous function.