lua-users home
lua-l archive

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


On Tue, May 31, 2011 at 15:23, steve donovan <steve.j.donovan@gmail.com> wrote:
If it was done nicely, with good documentation, it would make a useful
resource for LPeg users and could be wrapped up as a LuaRocks package.

A small trick for lpeg: rather than defining a slew of locals at the top of the script you can use the following prolog (compatible with both Lua 5.1 and 5.2, probably also with 5.0):

    local lpeg= require"lpeg"

    local _ENV = {__index = not getfenv and _ENV or getfenv(0)}
    -- "not getfenv": just in case an _ENV global is defined in 5.1

    for k,v in pairs(lpeg) do
        _ENV[k]=v
    end

    if setfenv then setfenv(1,_ENV) end

It is much clearer IMO, although it slows down the grammar building. The compiled grammar will be as fast as it would have been with locals.

If someone writes a Rock for a pattern library, he may want to add the following code to streamline the grammar setup:

    --- lpeg_pattern_library.lua

    local lpeg=require"lpeg"

    local lpeg_pattern_library = {
        -- the pattern library
        -- ...
    }

    lpeg_pattern_library.make_env = function (env1)
        local env2 = {__index = not getfenv and env1 or getfenv(2)}
        for k,v in pairs(lpeg) do env2[k]=v end
        for k,v in pairs lpeg_collection do env2[k] = v end
        return env2
    end

    return lpeg_pattern_library

    --- the grammar prolog becomes:

    local _ENV= require "lpeg_pattern_library".make_env( _ENV )
    if setfenv then setfenv( 1, _ENV ) end


-- Pierre-Yves