lua-users home
lua-l archive

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


>From: Supratik Champati <champati@sofy.com>
>
>How hard is it to add a switch statement to lua.

not too hard, but we don't think it's worth it, because we would do it in
full generality and not for numbers only. so, in the end, it would be very much
like a chain of if-then-elseif statements.

Norman Ramsey has modified Lua to include a case statement.
However, as far as I know, he used Lua 2.5 and hasn't moved to 3.1.

>using if then elseif statements - switch case statements would
>be more efficient and also more readable.

I agree with readbility, but not with efficiency. Remember that you're using
an interpreted language, which is already "slow" (however, Lua is said to be
one of the fastest extension languages around).

The "efficient" way in Lua is to *index* a table of functions. something like:

 action={
	 [1] = function (x) B1 end,
	 [2] = function (x) B2 end,
	 ["nop"] = function (x) B3 end,
	 ["my name"] = function (x) B4 end,
 }

then do

 action[x](x)

instead of

 switch (x)
 case 1: B1
 case 2: B2
 case "nop": B3
 case "my name": B4
 end

Not that the action table is more readable...
--lhf