lua-users home
lua-l archive

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


On Mon, Mar 23, 2009 at 8:03 PM, Geoff Leyland wrote:
> PiL says: "Unlike arithmetic metamethods, relational metamethods do not
> support mixed types...".  Supporting mixed types would be very handy
> for defining constraints in Linear Programs, where you could go:
>   a_constraint = 2 * x1 + 3 * x2 + 4 * x3 <= 6
> ...The pure Lua alternative I can think of is to offer easy constructors
> for term lists:
>  a_constraint = 2 * x1 + 3 * x2 + 4 * x3 <= make_term_list(6)

Even that won't work because, moreover, "these operators always result
in false or true." [1]  Therefore, a_constraint always assumes the
value true or false, not some expression object.

Your approach is fairly similar to [2], which has some limitations as
you have shown.  Here's a few alternatives:

  a_constraint = le(2 * x1 + 3 * x2 + 4 * x3, 6)
  a_constraint = (2 * x1 + 3 * x2 + 4 * x3):le(6)
  a_constraint = Constraint[[2 * x1 + 3 * x2 + 4 * x3 <= 6]]

I tend to like the last one since putting the expression into a string
you parse yourself allows much flexibility, few gotchas, and a
familiar syntax.  If you need to substitute Lua variables into those
expressions, it's a bit more cumbersome, but you might use the
approaches in [3,4] and take care about security concerns similar to
SQL injection.

Metalua[5], token filters, or patching Lua are other alternatives if
you want a more seamless syntax.

[1] http://www.lua.org/manual/5.1/manual.html#2.5.2
[2] http://lua-users.org/wiki/ExpressionTemplatesInLua
[3] http://lua-users.org/wiki/ListComprehensions
[4] http://lua-users.org/wiki/StringInterpolation
[5] http://metalua.luaforge.net/