Function Definitions
function-definition: export type id ( parameter-list ) function-propertiesopt function-body
export:
public
package
private parameter-list: parameter parameter-list, parameter function-body: { statement* } function-properties: : function-property+ function-property: modify thiscall stdcall abstract null = expr widening converter inline encrypted nonfglue intrinsic referred require super pure no return
Example:
public int funcName(int a, int b) : abstract {
statements
}
package void funcName(StrBuf buf) {
statements
}
Export
public
Able to be invoked from anywhere.package
Only able to invoked by code within the same directory (not including subdirectories).private
Only able to invoked in the same file.
Function Properties
Function definitions can list various properties to request special treatment or signal aspects of their behavior.
- Use the
inline
property to request inlining of all calls to the function. Use with caution since overuse may lead to very large function bodies.
- Use the
referred
property to turn off all warnings that the function appears to be unused.
- The
noreturn
property makes the function never return to the caller – it always throws an exception or performs some other form of non-local exit.
Currently optional.
- The
pure
property signals that the function is referentially transparent and that calls to it may be optimized or precomputed. A function is referentially transparent if the return value depends only on the parameters and not on any global state and the function lacks side effects. Only meant for the compiler developers.
Aliases
An alias
can be used to make a short-hand to a function definition.
function ( parameter-list ): type
This is often used with callback functions. For example, in cm/core/part/partHooks.cm :
/** * Raw hooks list. */ private alias completeListHook = function (Part[] list, Space space):Part[]; /** * Raw part hooks. */ private completeListHook{} completeListHooks : keep; /** * Append a complete part list hook. */ public void appendRawPartListHook(completeListHook hook) { if (hook) { if (!completeListHooks) init completeListHooks(); completeListHooks << hook; } }
Function Object
In CM, any function can be cast into a Function
object and vice versa:
private int normalFunction(int a, str b) { return a; } { Function functionObject = function normalFunction; if (function(int, str):int backToNormal = functionObject.:function(int, str):int) { pln(backToNormal(5, "")); } }
Comments
0 comments
Please sign in to leave a comment.