Skip to main content

Functions

Functions follow the common code pattern of the reserved name, the function name, parameters, and a code block.

function <name> (parameters) { }

function main() {
/*
This is a special type of function.
The main() function is the entry point to code execution
*/
}

The main function is the execution entry point. Other functions and definitions outside the main, but in the file are visible at a Global scope level.

The parameter of a function is the same as that of a TypeScript function. The parameters can be named and have default values.

function hello ({message="Hello World"}) {
printf("Main meessage ->, %s", message)
}

function main () {
hello()
hello({
message: "Goodbye",
unused: "field"
})
}

In this function, you call hello twice. The first time, there is no argument, so the system uses the default argument. The second time, there is a passed object that has a message field. In this case, the "Goodbye" value is presented.

Functions have proper scoping.

function called() {
let x = "local"
printf("%s", x)
// printf("%s", y)
}

function main () {
let x = "global"
let y = "global"
printf("%s", x)
called()
}

In the above example, the function called will print the local variable. However, if you tried to refer to the y variable in the called function, the compiler will give a variable undefined error.

case(condition_1, value_1, [condition_2, value_2, …​], default_value)

evaluate a list of conditions and returns the first value whose condition is evaluated to true. If all conditions are false, the default value is returned

let i = 10
case(i>10, "bigger than ten", i>=0, "positive", "negative") // return "positive"
let i = -10
case(i>10, "bigger than ten", i>=0, "positive", "negative") // return "negative"

template(text, variableMap)

Generates text output based on input variables. The template format is the same as Golang’s template. The variableMap is a map type holding variables or a json object.

let t = `Value of a: {{.fields.a}}
List: {{.list}}`
let opt = `{"fields":{"a":"foo"}, "list": [1234, 5678]}`
let s = template(t, opt)
// Value of a: foo
// List: [1234 5678]