LUA function closure

Words scoping: when another function nested within a function, the function can access local variables for external functions, such feature word is called scoping

    table.sort (names, functin (n1, n2) 
        return Grades [n1]> Grades [N2] 
    End) 
    // anonymous functions can access the interior of the external function n1, n2

The first class values: lua which is a function value, he can present variable, as a function of parameters, as a return value

Copy the code
    Test function () 
        local I = 0 
        return function () 
            I ++ 
            ... 
        End 
    End 
    // the return value as a function, also called I where outside the local variables is in lua upvalue
Copy the code

 

Closure: a function of internal plus external local variable (an upvalue) held by the external function external function (that is, plant) generated by calling an instance of function comprising

Closure Composition: upvalue + internal + external function function external functions created (closure function)

Example:

Copy the code
    Test function () 
        local I = 0 
        return function () // tailcall 
            I + =. 1 
            return I 
        End 
    End 
    C1 = Test () 
    C2 = Test () // C1, C2 is built in the same function, the same local variable the above two different instances of different closures 
            // closure of upvalue independently, a call test () will produce a new closure 
    Print (C1 ()) ->. 1 
    Print (C1 ()) - -> each invocation repeated calls 2 // remember the last value of the call, that is i = 1 has a 
    print (c2 ()) -> 1 // different closures so upvalue different     
    print (c2 ( )) -> 2
Copy the code

 

The use of closures in the iterator: iterator needs to hold the last call and the call of a successful state, just use a closure mechanism can be implemented

:( create iterators must pay attention to the iterator just a builder, and he himself without circulation)

Copy the code
     list_iter function (T) 
            local I = 0 
            local = n-table.getn (T) 
            return function () 
                I = I +. 1 
                IF I <= n-return the then T [I] End 
            End 
        End 
    // list_iter here is a plant, each call will generate a new closure of the inner closure includes an upvalue (T, I, n-) 
    // so that each function call of the closure once the closure so generated will be based on a state of recording, and return to list next
Copy the code

Using an iterator:

Press Ctrl + C to copy the code

Guess you like

Origin www.cnblogs.com/delphixe/p/11324830.html