This section presents advanced uses of functions and scoping, as well as their combo: lexical closures, which prove to be a very powerful tool.
Contrary to other languages from the C family, scopes are expressions: they can be used where values are expected, just as 1 + 1 or "foo". They evaluate to the value of their last expression, or void if they are empty. The following listing illustrates the use of scopes as expressions. The last semicolon inside a scope is optional.
Scopes can be nested. Variables can be redeﬁned in nested scopes. In this case, the inner variables hide the outer ones, as illustrated below.
Functions can be deﬁned anywhere local variables can — that is, about anywhere. These functions’ visibility are limited to the scope they’re deﬁned in, like variables. This enables for instance to write local helper functions like max2 in the example below.
A closure is the capture by a function of a variable external to this function. urbiscript supports lexical closure: functions can refer to outer local variables, as long as they are visible (in scope) from where the function is deﬁned.
function printSalaries(var rate)
var charges = 100;
function computeSalary(var hours)
// rate and charges are captured from the environment by closure.
rate * hours - charges
echo("Alice’s salary is " + computeSalary(35));
echo("Bob’s salary is " + computeSalary(30));
 *** Alice’s salary is 425
 *** Bob’s salary is 350
Closures can also change captured variables, as shown below.
Closure can be really powerful tools in some situations; they are even more useful when combined with functional programming, as described in Listing 9.