lua-users home
lua-l archive

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


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[1],

    switch(value) {
      case1 = function()
        -- no fallthrough
      end;
      case2 = function()
        -- regular fallthrough
        return fallthrough "case3"
      end;
      case3 = function()
        -- backward fallthrough
        return fallthrough "case1"
      end;
    }

[1] http://lua-users.org/wiki/SwitchStatement

-- 
tom <telliamed@whoopdedo.org>