Changes between Initial Version and Version 1 of Creating Closures with NQP-rx

Show
Ignore:
Timestamp:
03/16/10 03:22:58 (10 years ago)
Author:
Austin_Hastings
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Creating Closures with NQP-rx

    v1 v1  
     1The following code works as of Parrot 2.1 to create and store closures from NQP-rx. If you need this, please note that the `newclosure` op is necessary to clone the enclosed context. Also, you need to re-enter the containing lexical scope to reset the lex vars you want unshared. Otherwise, as shown (see `shared` vs. `not_shared`) they won't be shared. 
     2 
     3{{{ 
     4#! /usr/bin/env parrot-nqp 
     5 
     6MAIN(); 
     7 
     8sub MAIN() { 
     9        my @closures; 
     10        my @names := <fred wilma barney betty>; 
     11        { 
     12                my $shared := 1; 
     13 
     14                my $count := 1; 
     15                for @names -> $name { 
     16                        my $not_shared := 1; 
     17                         
     18                        my &sub := { 
     19                                say("$name\twas called $not_shared times. Any sub was called $shared times."); 
     20                                $shared++; 
     21                                $not_shared++; 
     22                        }; 
     23                         
     24                        @closures.push: pir::newclosure__PP( &sub ); 
     25                        $count++; 
     26                } 
     27        } 
     28 
     29        my $count := 0; 
     30        while $count < 3 { 
     31                for @closures { 
     32                        $_(); 
     33                } 
     34                 
     35                $count++; 
     36        } 
     37} 
     38}}} 
     39 
     40== Entering Scope == 
     41 
     42It is the act of _entering_ the lexical block that performs the allocation of a new lexpad and the other housekeeping associated with a new lexical environment (for you to enclose). You can get that effect in a number of ways: 
     43 
     44  * Calling a sub, obviously, enters its lexical scope when you call it. 
     45  * Recursion, naturally, qualifies as entering a new lexical scope. 
     46  * Executing a `for` or `while`/`until` loop, because these are implemented as subs. 
     47  * Executing an `if` or `unless` statement that contains lexical variable declarations. (Caution! If the block has no lexical vars, it will be 'in-lined' and not a separate sub.)