lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


on 9/15/05 10:42 AM, Rici Lake at lua@ricilake.net wrote:

> Lua functions are
> actually mutable objects -- you can call setfenv on them

Which is an annoyance in a variety of ways.

1. It cries out for a way to duplicate a function so that you can set the
environment for the duplicate without changing the original.

2. It interferes with the ability to perform some optimizations. For
example, if one has an anonymous local function being passed somewhere that
doesn't actually reference any upvalues, then it's instantiation could be
moved further out in the code were it not for the fact that setfenv
interferes with sharing the function. Example (which would be better written
using pairs, but I needed something simple):


    function dumpTable( t )
        table.foreach( t, function( k, v )
            DebugLog( "Entry %s --> %s", tostring( k ), tostring( v ) )
        end )
    end

This could be transformed into:

    local function dumpHelper( k, v )
        DebugLog( "Entry %s --> %s", tostring( k ), tostring( v ) )
    end

    function dumpTable( t )
        table.foreach( t, dumpHelper )
    end

In the first snippet, we instantiate the function on each call. In the
second snippet, we only instantiate it when we execute the chunk and then we
reuse that instantiation.

An optimizer could detect such cases and do the lifting were it not for the
fact that the different instantiations could end up with different
environments.

An alternative to setfenv which would be less powerful but would avoid these
issues would be to provide the environment as an argument to the chunk
compiler.

Am I recommending making that change? Probably not at this point, but if we
can't do so, then it might be nice to fully embrace the mutability of
functions and provide a way to duplicate them.

Mark