lua-users home
lua-l archive

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


Hi,

I did not find a C implementation for a switch-case statement so I made one on
my own. The implementation basically just imitates a sequence of ELSEIF's.
However, the expression is evaluated in a hidden variable only once, so it's faster
than using ELSEIF's. The first CASE is mandatory, everything else is optional.
DEFAULT must be the last branch if it's there.

Syntax:
selectstat -> SELECT val1 DO CASE val2: block {CASE valN: block} [DEFAULT: block] END

Fall through is not supported, nor is break or continue. It's really just a better
looking IF-ELSEIF statement.

To implement the statement, you will have to add the tokens SELECT, CASE,
DEFAULT as well as the respective TK_XXX constants. The rest is copy&paste.
And of course you need to add an entry point for TK_SELECT in lparser.c/statement().

Maybe someone finds this useful. I have not tested it much and it was implemented
rather quickly, so no guarantee for whatsoever. But if you find bugs, please notify
me.

BTW: You might see that subexpr() accepts one argument more than the one in
the official Lua distribution. This is an argument that I use to tell subexpr() that
the expression to parse is after a CASE statement. My version of subexpr() will only
allow constants then, because variables are not meant to be in a switch-statement.
If you use the normal Lua subexpr(), variables will be allowed in your CASE statements.

Andreas

Attachment: select_case.c
Description: Binary data