Quirrel4.41.0

types.Function.getfreevar

Method on every function
function.getfreevar(index: int): any

Returns the name and current value of one of the closure's free variables (the outer locals it captured when it was created).

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

indexintwhich free variable to read, 0 to freevars - 1

Return value

A table with two keys: name, the free variable's name as written in the source, and value, its current value.

Errors

Throws Invalid free variable index when index is negative or at least as large as the closure's freevars count (see getfuncinfos), including on a closure that captured no free variables.

Notes

A native closure ordinarily has no free variables to report, so any index throws on one; the rare native closure built with bound outer values (only possible from the C API) reports each one with the placeholder name @NATIVE instead of a real source name.

Reading a free variable does not affect it: two closures that captured the same outer local still share it, and a later assignment inside either one is visible through getfreevar on both.

Example

examples/types/function/getfreevar.nut
local x = 10
let function foo() { return x }
let fv = foo.getfreevar(0)
println($"{fv.name}={fv.value}")
x = 99
println("foo.getfreevar(0).value =", foo.getfreevar(0).value) // reads the live variable, not a snapshot
try { foo.getfreevar(1) } catch(e) { println("foo.getfreevar(1) throws:", e) }
Output:
x=10
foo.getfreevar(0).value = 99
foo.getfreevar(1) throws: Invalid free variable index

See also

getfuncinfosReturns a table describing the closure: its name, parameters, and other introspection data the VM tracks for it.
bindenvReturns a copy of the closure with env statically bound as its this: every future call to the copy uses env, no matter how it is called.
functionclass index