lua-users home
lua-l archive

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


On Sun, Sep 11, 2011 at 6:55 PM, Geoff Leyland <geoff_leyland@fastmail.fm> wrote:
On 12/09/2011, at 10:51 AM, Peter Pimley wrote:

> Dear Lua list,
...
> The best I can come up with is to use an anonymous "converter"
> function, something like:
>
> f = {
>  func = function(p) foo (p[1], p[2]) end,
>  params = {23, 42}
> }

Doesn't unpack do what you want?

$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> function a(b, c)
>> print(b, c)
>> end
> a(unpack{1,2})
1       2



I'd prefer a __call metamethod for something like this. Much easier to work with, especially if you're storing params or other information for more than one function. Here's the way:

foo = setmetatable({}, {
    __call = function (self,a,b,reset)
        self[1] = a ~= nil and a or self[1] -- store args if supplied, as long as they're not nil
        self[2] = a ~= nil and b or self[2] -- you can also supply defaults if needed here
        if reset then self[1] = nil; self[2] = nil end -- optional if you want to reset the stored args, just omit this part and the 'reset' arg if you don't feel the need
        DoWhatEver(self[1],self[2])
    end
})

-- Usage/example
DoWhatEver = function (a,b) print(a,b) end
foo()
foo(123, 456)
foo()
for k,v in pairs(foo) print(k,v) end
print(foo[1], foo[2])

-- Output
nil    nil -- foo()
123    456 -- foo(123, 456)
123    456 -- foo()
1    123 -- pairs loop 1
2    456 -- pairs loop 2
123    456 -- foo[1], foo[2]

-- Conclusion

A __call metamethod allows you to treat a table as a function, which allows for all sorts of neat stuff - Least of which being a very easy way to store parameters passed to the function.