lua-users home
lua-l archive

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


On 10/30/07, Diego Nehab <diego@tecgraf.puc-rio.br> wrote:
> In many of
> those cases, I suspect it would be possible to support the
> required semantics with Lua constructs, if only it was
> possible to translate their syntax in a simple way.  Maybe
> there is a niche for Lua-based languages here.

http://lua-users.org/wiki/LuaMacros

Here is something more useful and less frivolous. Luiz mentioned that
a full macro system was possible using the token filter patch, and so
I wrote a Lua macro preprocessor. Important to emphasize that this is
_not_ a separate pipeline process, rather one loads Lua modules which
control the compilation of further modules, etc (as did the
scary-braces module but that's another issue ;))

$ lua -lmacro -lmacro-defs test-macro.lua

In particular, this scheme works with the usual command prompt.

These are smart macros, so if you don't provide parameters, you can
specify a function to create the parameters.  It's then possible to
define something useful like try..except

---- implementing try...except
local try_except_stack = {}
local push = table.insert
local pop = table.remove
function name(x) return {'<name>',x} end

macro('try',{'L1','L2'},
       @ local L1,L2 = pcall(function() @,
       function()
               local L1 = get_global()
               local L2 = get_global()
               push(try_except_stack,{L1,L2})
               return name(L1),name(L2)
       end)

macro('except',{'L1','L2'},
       @ end) if not L1 then local e = L2 @,
       function()
               local t = pop(try_except_stack)
               if not t then error("mismatched try..except") end
               return name(t[1]),name(t[2])
       end)

So

a = nil
try
  print(a.x)
except
  print('exception:',e)
end

would translate as

a = nil
local _1ML,_2ML = pcall(function()
 print(a.ex)
end) if not _1ML then local e = _2ML
 print('exception',e)
end

A note on the @ ... @ weirdness; this is a token literal, which I
introduced because otherwise I would have to tokenize substitution
strings beforehand, which is a delicate business.

Here is an example where being able to add a little sugar helps
regular Lua syntax, and allows us to test different brands of sugar
before choosing one.

Of course, I have to give the usual health warnings about too much
sugar, and I've done enough C++ to know that macros are best avoided.
Here is the classic example of macro madness, Bourne's orginal Unix
shell code:

http://minnie.tuhs.org/UnixTree/V7/usr/src/cmd/sh/cmd.c.html

Apparently the man really missed Algol 68!

steve d.