lua-users home
lua-l archive

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




On 11/29/06, John Hind <john.hind@zen.co.uk> wrote:
I'm working on a calculator program which uses Lua as its _expression_
evaluator. I'd like to be able to offer extensible infix operators so
you'd be able to write something like:

c = a func b

where a and b are numeric variables or expressions and func is a
function. This would be evaluated as:
c = func(a, b)

For now, you can do it this way in metalua:

mlp.lexer.register "func" -- register "func" as a keyword
mlp.expr.add_infix{
  keyword = "func", -- operator name
  prec = 40, -- precedence
  assoc = "left", -- associativity: left, right or none (default is "left")
  builder = |x| +{ func( -{x[1]}, -{x[2]} ) } -- _expression_ builder
}

prec is the precedence of the operator, you can find other precedences in mlp_expr.lua, and *maybe* in the doc.
If the builder looks too scary, you might prefer the equivalent no-syntax-sugar, no-quasi-quotes version:

function (x) return `Call{ `Id "func", x[1], x[2] } end

But this is far from perfect:
- "func" is now a keyword;
- you have to do this for every function you want to use as prefix/infix/potfix operators

I really like Haskell's solution, which allows to put arbitrary functions in infix position, if you put it between backquotes, as in: "a `func` b". Unfortunately, it clashes with my syntax for algebraic datatypes, so until I can think of an alternative syntax that doesn't look too awful and isn't ambiguous with something else, I won't add it. If you've got suggestions...

You can modify the parser more substantially to support arbitrary infix notations, but you'd quickly run into ambiguous syntaxes if you want it to still parse real Lua code. That might be acceptable for you if you only use it  with a limited subset of Lua.

The best solution would probably be to create a separate math expressions parser, so that you don't mess up your regular Lua _expression_ syntax, but you'd have to wait until I've properly documented the grammar generator. Meanwhile you can ask for support through private mail.