Functions inside functions

Syntax and values

A function can contain another function. The inner function remembers the surrounding variables it uses, even after the outer function has finished. This is called a closure. Think of the inner function keeping access to its own score card.

It remembers the variables, not a frozen copy of their first values. In the example, the same counter changes value on each call, so it prints 11, then 12. A new call to makeCounter creates a separate counter.

Lexical environment means the names available where a function is written. It does not depend on who calls the function. First-class means functions are values you can save in a variable, pass to another function, or return. An anonymous function, also called a lambda, would have no declared name; Pliro currently requires named function declarations.

User functions close over their lexical environment:

# language: en
function makeCounter(start):
    let value = start

    function next():
        set value = value + 1
        return value

    return next

let counter = makeCounter(10)
say counter()
say counter()

Functions are first-class runtime values: they can be stored, passed, returned,
and called. There is no anonymous-function or lambda syntax.

Syntax and values · Built-ins · Programming guides