lua-users home
lua-l archive

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

Hi guys,

This is obviously a perenial topic, since there's a wiki page dedicated to it:

My feeling is that switch is the wrong model; we should look at
Pascal's case statement as more appropriate inspiration. Here are some
possible forms:

    case (k)
      is 10,11: return 1
      is 12: return 2
      is 13 .. 16: return 3	
      else return 4
        matches '^hell': return 5
        matches '(%d+)%s+(%d+)',result:
            return tonumber(result[1])+tonumber(result[2])
        else return 0

You can provide a number of values after is, and even provide a range
of values. matches is string-specific, and can take an extra parameter
which is filled with the resulting captures. This is implementable
using token filter macros so people can get a feeling for its use in

(See, which has been
semi-officially released  - the downloadable source zip contains an
example implementation. Unfortunately, there is a gotcha; Lua
complains of a malformed number if there is no whitespace around
'...'. Also 'result' has to be global. These are implementation
irritations, not relevant to a design discussion, I think),

This case statement is a little bit of syntactical sugar over a chain
of elseif statements, so its efficiency is the same.  What the
compiler actually sees in the first case is:

     do local __case = k; if false then
     elseif __case == 10 or __case == 11 then return 1
    end; end

But already I've thought of some other possibilities. This feels a
little more elegant.

case (k)
  is 10 or 11: return 1
  is 12: return 2
  is between(13,16): return 3
  else return 4

What do you think?

steve d.