lua-users home
lua-l archive

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


And even uglier one, that can handle arithmetic brackets, but reusing lua's { }

very crude

local function infix(...)
   local function eval(t)
      local l = t[1]
      if type(l) == "table" then l = eval(l) end
      for k = 2,#t,2 do
	 local f, r = t[k], t[k+1]
	 if type(r) == "table" then r = eval(r) end
	 l = f(l, r)
      end
      return l
   end
   return eval(...)
end

local function add(a,b)
   return a + b
end

local function sub(a,b)
   return a - b
end

local function mul(a,b)
   return a * b
end

local function div(a,b)
   return a / b
end

-- Here be { brackets, not (
print( infix{ 12 ,add, 3 ,add, 10 ,sub, { 30 ,mul, 10 } } )



On 12/18/11 1:11 AM, HyperHacker wrote:
2011/12/18 Dimiter "malkia" Stanev<malkia@gmail.com>:
-- Here is a very poor attempt :)

local function infix(...)
   local args = {...}
   local nargs = #args
   local r = args[1]
   for k=2,nargs,2 do
      r = args[k](r, args[k+1])
   end
   return r
end

local function add(a,b)
   return a + b
end

print( infix( 12 ,add, 3 ,add, 10 ) )



On 12/17/11 9:23 PM, Xavier Wang wrote:
hi robero and list,

i'm inspired by the post about implement c enum. somebody said the
getflags function shoud return a userdata to implement a contains
function. i think its a good idea, excerpt a details: thus will allocate
memory.

i'm run lua on a embedded system, embedded systemembedded system, nokia
n73 cellphone. my game will lag if i allocate memory in draw function
since the garbage collection. so we avoid any memory in event loop. but
i really miss the contains function, so i think a syntax allow use
function as infix operator will be great.

e.g. if i have a function add(a, b), i can call it with a `add` b, its
a syntax sugar of add(a,b)

its very simple and can used in many situations, e.g. bitop calls, and
flags contains test.

has anybody agree me? i hope this feature can appear on lua5.3 :)

thanks everybody~




I had done some hacking of metatables to make the following valid syntax:
foo = (3) '<<' (x)

It's still pretty ugly and not terribly efficient, but it works... :p