Open yngvar-antonsson opened 3 years ago
It may be a good idea. In other words, we need to save not only the function itself but its arguments too.
But it may be challenging. Suppose I want to create a closure, like this:
function closure(fn, ...)
return function()
return fn(...)
end
end
fn = closure(math.sqrt, 4) -- returns a function which can be called without arguments
fn() -- returns 2
But Lua doesn't allow to do so:
closure.lua:3: cannot use '...' outside a vararg function near '...'
The solution is the following:
function closure(fn, ...)
local args = {n = select('#', ...), ...}
return function()
return fn(unpack(args, 1, args.n))
end
end
fn1 = closure(print, 'a', 'b', 'c')
fn2 = closure(print, 3, 4, nil)
fn1() -- prints "a b c"
fn2() -- prints "3 4 nil"
Look, it doesn't even lose a nil.
It would be nice to write one-line hooks like
in such way: