Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Scoping and Lifetimes

Subscoping

A “subscope” is a scope contained inside a function, created inside curly braces ({}).

Subscopes can view and modify variables avaliable in their parent scope.

Subscopes may also create their own variables, however these will be destroyed when the subscope ends.

Function Scoping

A function scope is a scope created inside a function.

Function scopes are created from a function’s attached closure, which is a snapshot of all variables at the time of function definition.

The function’s attached closure cannot be modified.

Function scopes also contain all arguments provided to a function.

When the function finishes running (with a return), all variables are destroyed.

Destructors

Objects (see here) can contain a destructor which specifies custom behaviour for destroying itself. This is useful for:

  • Freeing heap-allocated memory
  • Closing a connection
  • Closing a file

The destructor will always be in the field destructor with type signature fun() int. It should be automatically called when the variable goes out of scope.

Duplicators

Objects (see here) can contain a duplicator which specifies custom behaviour for copying itself. This is useful for:

  • Duplicating heap-allocated memory

The duplicator will always be in the field duplicator with type signature fun((self) old) (self). It should be automatically called when the variable is:

  • Copied into a new variable
  • Put inside a closure
  • Passed to a function