lua-users home
lua-l archive

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


Hi all,

This is a new version of LuaMacro, which is an LPeg-based lexical
macro preprocessor for Lua.  Main new features are

- tracking line numbers (not _entirely_ flawlessly, but good enough for now)
- support for C preprocessing (thanks to Peter Odding's LPeg C lexer)
- actual documentation
- limited support for code patching

The last feature allows a very natural style of writing modules:

require_ 'module'

function one() return two() end
function two() return 42 end

which is translated into:

local one,two
do
function one() return two() end
function two() return 42 end
end
return {one=one,two=two}

If such a module was named mod.m.lua, then the custom package loader
set by luam will do a preprocess-and-load.

One area that macrofied syntax can be useful is when testing.

require_ 'assert'
assert_ 'hello' == "hello"
assert_ {one=1,two=2} == {two=2,one=1}  --> does tables!
assert_ ('hello'):find 'll' == (3,4)   --> and multiple values
assert_ "hello" matches "hell"
a = nil
assert_ a.x throws "attempt to index global"

(This was inspired by Scala Test)

The begin..end notation discussed recently is simply:

def_ begin (function() _END_CLOSE_

so that 'fun begin .. end' becomes 'fun (function() .. end)'

We were also talking about a 'lazy' keyword. Well, a tool like
LuaMacro allows you to test out the concept interactively

-- lazy.lua
local M = require 'macro'
M.define('lazy',function(get)
    get() -- skip space
    local expr,endt = get:upto(function(t,v)
        return t == ',' or t == ')' or t == ';'
          or (t=='space' and v:match '\n')
    end)
    return 'function(_) return '..tostring(expr)..' end'..tostring(endt)
end)

$> luam -llazy -i
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
Lua Macro 2.3.0 Copyright (C) 2007-2011 Steve Donovan
> function test(f) return f() end
> = test(lazy 23)
23

(LuaMacro has been tested with Lua 5.1.4, LuaJIT 2.0.0 Beta8 and Lua
5.2 beta - just needs LPeg)

github: https://github.com/stevedonovan/LuaMacro
zip: http://stevedonovan.github.com/files/luamacro-2.3.0.zip
readme: http://stevedonovan.github.com/LuaMacro/docs/index.html
ldoc: http://stevedonovan.github.com/LuaMacro/docs/api.html

steve d.