lua-users home
lua-l archive

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


What about just like C++'s lambda syntax?

table.sort(t, _1 > _2)

_1 and _2 has a metatable to generate syntax tree on-the-fly. and when __call is called, the syntax tree is translated into lua function.


2014-05-26 9:24 GMT+08:00 Philipp Janda <siffiejoe@gmx.net>:
Am 26.05.2014 02:39 schröbte Rena:

Just hacked this up on a whim:


function L(c)
     return assert(loadstring(
         "local args={...}; return " .. c:gsub('%$(%d+)', 'args[%1]')
     ))
end

local t={'bananas', 'watermelons', 'pears', 'grapes'}
table.sort(t, L"$1 > $2")
for k,v in pairs(t) do print(k,v) end


Traditionally[1], the function is called `fn` and uses P1-P9 for parameters and L1-L9 for upvalues.



Maybe it's not the most elegant (hope your function never uses a $ in a
string) but I thought it was a neat little hack and a bit nicer looking
than:
table.sort(t, function(a, b) return a > b end)


Philipp

  [1]: http://lua-users.org/wiki/ShortAnonymousFunctions







--
regards,
Xavier Wang.