lua-users home
lua-l archive

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


"Javier Guerra" <javier@guerrag.com> writes:

> On 11/7/07, Tim Johnson <tim@johnsons-web.com> wrote:
>> 3)Can one use a lua table to "dispatch" one of a list of alternative
>> choices. Would such an approach be "messy"? ....
>
> sure, i do this all the time (and i'm sure many others).
>
> also, since in Lua functions are really anonymous (unlike Python), it
> doesn't pollute any namespace (the table itself is the namespace)
>
>
> -- easy to write...
> local dispatch = {
>    start = function (x) .... end,
>    continue = function (x) ..... end,
> .....
> }
>
> dispatch[state](x)             -- and easy to call!

That still does pollute the (local) namespace by using "dispatch".
But you could write

({
    start = function (x) .... end,
    continue = function (x) ..... end,
 .....
})[state](x)

And for such a dispatcher, you would likely not pass an argument,
anyway, but use upvalues.  So it would rather be
({
    start = function () .... end,
    continue = function () ..... end,
 .....
})[state]()

-- 
David Kastrup