×

Discussion Board

Results 1 to 2 of 2
  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    14

    unexpected e32.ao_sleep behavior

    Can anyone explain to me why executing this snippet of code:
    Code:
    import sys, e32
    
    for i in range(5):
        e32.ao_sleep(0, lambda: sys.stdout.write("%d\n" % i))
    
    e32.ao_sleep(4)
    results in this output?
    Code:
    4
    4
    4
    4
    4
    Regards,
    Albert

  2. #2
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    The lambda closes over the variable i, which is assigned the values 0, 1, 2, 3 and then 4 successively by the for-loop. It turns out that all of your callbacks executed after i already had the value 4. (This behavior is different from Lisp, where each iteration of such a loop effictively defines a different variable i.)

    Here's one solution:
    Code:
    for i in range(5):
        e32.ao_sleep(0, lambda i=i: sys.stdout.write("%d\n" % i))
    Here's another:
    Code:
    for i in range(5):
        def callback(i=i):
            print i
        e32.ao_sleep(0, callback)
    And here's another:
    Code:
    def async(i):
        e32.ao_sleep(0, lambda: sys.stdout.write("%d\n" % i))
    
    for i in range(5):
        async(i)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×