Since Lua supports first-class functions, I'd like to know if you can desugar operators, like in many functional languages. E.g in OCaml you can do:
let x = (+) 3 5
The code above inits the variable x
with the value 3 + 5
. Writing (+)
is equivalent of having a local function that takes two parameters and returns their sum. (+) 3 5
is calling this function with the two arguments 3
and 5
.
The motivation behinds this is that you can pass the operator directly to a function without having to wrapped it in a function before:
local t = {"ab", "d", "c" }
local function op_greaterthan (a,b) return a>b end
table.sort (t, op_greaterthan) --would like to write: table.sort (t, (>))
Thanks!
You can't.
The Lua interpreter is very small, and it "makes shortcuts" when dealing with operators; for the parser, they are simply not "functions".
If you try to use an operator without its params, like this:
Then the interpreter will throw a syntax error.
Due to this implementation, you are limited to the options already discussed: either you use a wrapper function (such as
add
) or you pass in a string and so some kind ofeval
, as in jpjacobs' solution.