I now see I made some errors (I explain below)

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)

THIS should be done with a .pcc_begin/end_return pair, and with use of a .return statement:


   P5 = clos

.end

.sub _function
   # i = i + 1
   .local pmc j
   find_lex j, "i"
   j = j + 1

THIS print should not be here:

   print j
   store_lex -1, "j", j
   # return i

THIS should be enclosed in .pcc_begin/end_return pair:


.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



WHoops, I see I made a mistake:

1. it didn't work, like I thought. There was some print statement which shouldn't be there, which caused me thinking it worked.
2. "P5 = clos" can be replaced by a .pcc_begin/end_return pair.


So, I think I 've got my answer there !

thanks anyway,
klaas-jan




Reply via email to