Leopold Toetsch wrote:

Klaas-Jan Stol <[EMAIL PROTECTED]> wrote:

Hello,


I've been playing with closures and subs but I have a little bit of
trouble with those.


newsub $P0, .Closure, _foo $P0(q) newsub $P0, .Closure, _foo $P0(q)

Closures have to be distinct.


leo



Thanks for your quick reactions.
Indeed, doing

$P0(q)

works ok. I'm a bit confused by syntax then (but I think it makes sense now, if IMCC sees the "(", it is expecting args I guess)

In the mean time, I wrote another example for closures (maybe I should collect these in a HOWTO document :-)
(This one *is* working, however, again I don't understand why some things have to be done in a particular way)


First, I show the Lua code:

function newCounter ()
local i = 0
return function () -- anonymous function
i = i + 1
return i
end
end
c1 = newCounter()
print(c1()) --> 1
print(c1()) --> 2


This is the translation (and it works! :-)

.sub _newcounter
   new_pad 0
   # local i = 0
   .local pmc i
   i = new .PerlInt
   i = 0
   store_lex -1, "i", i

# create closure of "function" to return
.local pmc clos
newsub clos, .Closure, _function
# why should I do this? (should I?) ".return clos" does not work (then it's whining about "SArray" again)
P5 = clos


.end

.sub _function
# i = i + 1
.local pmc j
find_lex j, "i"
j = j + 1
print j
store_lex -1, "j", j
# return i
.return j .end


.sub _main @MAIN
# c1 = newcounter()
.local pmc c1
c1 = _newcounter()
# print(c1()) Prints 1
.local pmc i i = c1()
print i
print "\n"


   # print(c1())   Prints 2
   i = c1()
   print i
   print "\n"

   # print(c1())   Prints 3
   i = c1()
   print i
   print "\n"
   end
.end

So, this one works. I guess my question concerns syntax: why doesn't ".return clos" in newclosure() work?

Klaas-Jan



Reply via email to