lua-users home
lua-l archive

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


   Here's yet another implementation of a "switch" statement.
This one is based on Luiz Henrique de Figueiredo's switch statement
presented in a list message dated Dec 8 1998, but the object/method
relationship has been flipped around to achieve a more traditional
syntax in actual use.  Nil case variables are also handled - there's
an optional clause specifically for them (something I wanted), or
they can fallback to the default clause.  (easily changed)  Return
values from the case statement functions are also supported.

  function switch(c)
    local swtbl = {
      casevar = c,
      caseof = function (self, code)
        local f
        if (self.casevar) then
          f = code[self.casevar] or code.default
        else
          f = code.missing or code.default
        end
        if f then
          if type(f)=="function" then
            return f(self.casevar,self)
          else
            error("case "..tostring(self.casevar).." not a function")
          end
        end
      end
    }
    return swtbl
  end
 
  -- here's sample usage:

  c = 1

  switch(c) : caseof {
      [1]   = function (x) print(x,"one") end,
      [2]   = function (x) print(x,"two") end,
      [3]   = 12345, -- this is an invalid case stmt
    default = function (x) print(x,"default") end,
    missing = function (x) print(x,"missing") end,
    }

  -- also test the return value
  -- sort of like the way C's ternary "?" is often used
  -- but perhaps more like LISP's "cond"
  --
  print("expect to see 468:  ".. 123 +
    switch(2):caseof{
      [1] = function(x) return 234 end,
      [2] = function(x) return 345 end
    })