types.Function.bindenv
Returns 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.
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
env | table|instance|class | a table, class or instance to bind as this |
Return value
A new closure. The original is unchanged.
Errors
Throws parameter 1 of 'bindenv' has an invalid type when env is not a table, class or instance - an array is rejected too, even though it is a valid environment for other purposes in the language.
Notes
The bound closure keeps only a weak reference to env. If nothing else keeps a strong reference to it, env can be collected before the closure is ever called, and this reads back as null inside the call:
let f = (function() { return this }).bindenv({tag = "temporary"})
f() // null: the table literal had no other owner
Give the environment a named local (or another strong owner) for as long as the bound closure needs it.
Example
function whoami() { return this.name }
let env = {name = "Alice"}
let bound = whoami.bindenv(env)
println("bound() =", bound()) // Alice, however bound() is called
println("{greet = bound}.greet() =", {greet = bound}.greet()) // still Alice, not the table it was read from
// the environment is held only weakly
let temp = (function() { return this }).bindenv({name = "Temporary"})
println("typeof temp() =", typeof temp()) // null: the table literal had no other ownerOutput:
bound() = Alice
{greet = bound}.greet() = Alice
typeof temp() = nullSee also
call | Calls the closure, using env as its this and forwarding the rest of the arguments as its own parameters. |
getfreevar | Returns the name and current value of one of the closure's free variables (the outer locals it captured when it was created). |
| function | class index |