[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Switch/Case with Fallthrough
- From: Tom N Harris <telliamed@...>
- Date: Wed, 20 Nov 2013 16:05:51 -0500
On Wednesday, November 20, 2013 01:46:24 PM Rena wrote:
> switch/case is something I often miss in Lua. You can do the same with a
> table of functions but it's a lot uglier. (And probably a lot less
> efficient due to the overhead of creating a bunch of functions and the
> table to hold them, vs what translates to a few if/else statements.)
I'm of the opposite opinion that jump tables are much more sensible (and C
compilers these days use them for switch if there's more than a ~4 cases.)
In particular, I think fallthrough is a misfeature that makes switch
statements difficult to read and can lead to bugs if the author doesn't
pedantically comment the blocks with /* fallthrough */. Using a table of
functions in Lua does allow explicit fallthrough in the form of tail-calls.
And you can even chain to any arbitrary function.
Using one of the forms described on the wiki,
case1 = function()
-- no fallthrough
case2 = function()
-- regular fallthrough
return fallthrough "case3"
case3 = function()
-- backward fallthrough
return fallthrough "case1"