[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Select (Switch) Case statement
- From: Warren Merrifield <wmerrifield@...>
- Date: Wed, 1 Sep 2004 16:47:55 +0100
True, that does look very cryptic, but if you wrap it all up with real
names, I think that it's not too odd, really. And learning to think
like this is a key to using Lua well, IMHO. I've used the foo["bar"]
syntax here, rather than foo.bar, as I think it's clearer in this
instance.
-- Example switch. I've put it inside it's own function for clarity.
function doswitch(case)
-- I'll assert here, but you could default by calling another
-- function if the case argument is nil.
assert(type(case)=="string");
local switch = {};
switch["attack"] = function()
-- Either write the attack behaviour in here, or refer to
-- an external function library here.
end
switch["defend"] = function()
-- Either write the defend behaviour in here, or refer to
-- an external function library here.
end
return switch[case]();
end
-- Example usage
state = "attack";
action = doswitch(state);
On Wed, 1 Sep 2004 18:38:54 +0300, Asko Kauppi <asko.kauppi@sci.fi> wrote:
>
> Face it, that looks really cryptical for the newcomer.
>
> Personally, I would welcome select/case/default into the language, but
> then again, using lookups (in other ways than what you describe here)
> generally diminishes the need itself for a switch statement. But it
> wouldn't hurt, either.
>
> -ak
>
> 1.9.2004 kello 18:00, David Given kirjoitti:
>
>
>
> > I may be being a killjoy, but:
> >
> > ({
> > [0] = function ()
> > print(0)
> > end,
> >
> > [1] = function ()
> > print(1)
> > end
> > }[value] or function ()
> > print("default")
> > end)()
>
>