In Tengo, functions are first-class citizen, and, it also supports closures, functions that captures variables in outer scopes. In the following example, the function returned from `adder` is capturing `base` variable.
```golang
adder := func(base) {
return func(x) { return base + x } // capturing 'base'
}
add5 := adder(5)
nine := add5(4) // == 9
```
> [Run in Playground](https://tengolang.com/?s=fba79990473d5b38cc944dfa225d38580ddaf422)
## Flow Control
For flow control, Tengo currently supports **if-else**, **for**, **for-in** statements.
```golang
// IF-ELSE
if a <0{
// ...
} else if a == 0 {
// ...
} else {
// ...
}
// IF with init statement
if a := 0; a <10{
// ...
} else {
// ...
}
// FOR
for a:=0; a<10;a++{
// ...
}
// FOR condition-only (like WHILE in other languages)
for a <10{
// ...
}
// FOR-IN
for x in [1, 2, 3] { // array: element
// ...
}
for i, x in [1, 2, 3] { // array: index and element
// ...
}
for k, v in {k1: 1, k2: 2} { // map: key and value
b[1] = "foo" // error: 'b' references to an immutable array.
b = "foo" // ok: this is not mutating the value of array
// but updating reference 'b' with different value
```
Not that, if you copy (using `copy` builtin function) an immutable value, it will return a "mutable" copy. Also, immutability is not applied to the individual elements of the array or map value, unless they are explicitly made immutable.
An error object is created using `error` expression. An error can contain value of any types, and, the underlying value can be read using `.value` selector.
if is_error(err1) { // 'is_error' builtin function
err_val := err1.value // get underlying value
}
```
> [Run in Playground](https://tengolang.com/?s=5eaba4289c9d284d97704dd09cb15f4f03ad05c1)
## Modules
You can load other scripts as modules using `import` expression.
Main script:
```golang
mod1 := import("./mod1") // assuming mod1.tengo file exists in the current directory
// same as 'import("./mod1.tengo")' or 'import("mod1")'
mod1.func1(a) // module function
a += mod1.foo // module variable
//mod1.foo = 5 // error: module variables are read-only
```
`mod1.tengo` file:
```golang
func1 := func(x) { print(x) }
foo := 2
```
Basically, `import` expression returns all the global variables defined in the module as a Map-like value. One can access the functions or variables defined in the module using `.` selector or `["key"]` indexer, but, module variables are immutable.
Also, you can use `import` to load the [Standard Library](https://github.com/d5/tengo/blob/master/docs/stdlib.md).