Capy-Bearer Documentation

function value

Capy

function(parameter_type, ...) result_type

A function can be stored in a variable, passed to another function and returned from one. The type is written as the parameter list and result, with no name.

function double(value : s32) s32
{
	-> value * 2
}

function apply(value : s32, transform : function(value : s32) s32) s32
{
	-> transform(value)
}

function RENDER()
{
	print(apply(21, double), "\n")
}

Output

42

Closures

A lambda written inline captures the locals it reads:

function RENDER()
{
	var offset := s32(10)
	var shift := function(value : s32) s32
	{
		-> value + offset
	}
	print(shift(5), "\n")
}

Output

15

A captured number, Boolean, or string keeps its value when the closure is created. Reassigning offset afterward does not change that captured value.

A captured array, any, or struct shares the original object. Mutating its contents through the closure changes what the caller sees. Reassigning an outer variable does not replace the closure's captured binding. Captured values stay alive as long as the closure needs them. The closure cannot reassign a captured binding.

Where they are used

The collection helpers take function values: map, filter, each, find, some, every and sort all accept a callback whose signature the compiler checks at the call site. That check is why map over an array and map over an any are separate overloads — the callbacks differ.

var offset := s32(10)
var shift := function(value : s32) s32
{
	-> value + offset
}
print(shift(5), "\n")

Output

15