E4151#
Values of type FuncRef[T] must be closed function -- it should not capture any local variables.
MoonBit provides a builtin type FuncRef[T], which represents closed function of type T.
In MoonBit's native backend, FuncRef[T] corresponds to function pointer type,
so FuncRef[T] can be passed to C FFI functions requiring a callback directly, for example setting UNIX signal handler.
Values of type FuncRef[T] must be closed function type,
if a function which captures free variables or a non-function is supplied, an error will be reported.
Erroneous example#
test {
let x : Int = 42
let _ : FuncRef[() -> Unit] = fn () { println(x) }
}
Suggestion#
If your callback function really needs to have captures, consider adding the captures as extra parameters to the function.
Otherwise, use a closed function that does not capture local variables:
pub fn callback() -> FuncRef[() -> Unit] {
fn() {
println(42)
}
}