Shelby Moore wrote:
Are closures in NekoVM broken in a very harmful way? Read to the bottom...
<snip>
However, NekoVM does not correctly implement closures:
http://nekovm.org/lua?s=closure#closures
NekoVM is copying the closure variables instead of saving a reference to a
shared copy, and thus there is no way to correctly use externally scoped
(shared by other scopes) variables.
How is anyone going to implement recursion or tree graphs on asynchronous
events/resources in NekoVM, when each function closure gets its own
private copy of the data structure? Thus I think it is impossible in
NekoVM?
<snip>
No, not impossible. I ran into this problem myself, as I wanted closures
in my language to behave more like Lua closures, where variables inside
a closure can reference variables in a lexically enclosing scope
Essentially, you just do as this post suggests:
http://lists.motion-twin.com/pipermail/neko/2005-August/000470.html
Variables that need to be accessed inside a function are turned into
members of an array. Modifying the array members inside the function
modifies the values outside the function as well.
var a = $array(2)
a[0] = "hello"
a[1] = "world"
var f = function(string) {
a[0] = string
}
f("goodbye")
$print(a[0]) //prints "goodbye"
It took some effort to get this done efficiently (that is, not turning
_every_ variable into an array member, but just those that need to be),
but it does work.
-Justin
--
Neko : One VM to run them all
(http://nekovm.org)