1

Given the following code

for i in range(10):
  touchManager.AddButton( {t | _i = i; StartLevel(_i) } )

def StartLevel(level):
  print level

I'd like the _i variable to hold the i value, but not beeing overwritten in the next iteration. How can i achive that?

Diego Dorado
  • 398
  • 4
  • 12

1 Answers1

0

Documentation says that closures have "read and write access" to their context. That means your closure will use reference to i each time it is executed, not store value each time it is defined.

I'm not sure that there's no standard way to save value inside closure - boo language documentation is VERY poor. The best thing you can do is asking some of the developers directly (some of them are available in boo google group).

Howerver, you can always achieve desired behavior by explicitly defining callable class:

class MyClosure(ICallable):
    i as int
    def constructor(i as int):
        self.i=i;
    def Call(o as (object)):
        StartLevel(i)

and then using it like that:

for i in range(10):
  touchManager.AddButton( MyClosure(i))

You can also try to define a macro which will automatically generate such closure classes, but it will be rather challenging (here are some links regarding macros):

http://boo.codehaus.org/Syntactic+Macros

https://groups.google.com/forum/#!topic/boolang/9wDEevRUHH8

user1875642
  • 1,303
  • 9
  • 18