Case

From OpenEUO
Revision as of 13:15, 2 November 2010 by Ximan (Talk | contribs) (Description)

Jump to: navigation, search

Calling Pattern

Call

local c = sl.case(casetable)

Args

casetable is a table, where keys are any type and values are functions

Results

c is a case closure

Closure Methods

Example Usage

local t = 
  {
  [1]     = function(...) local a={...} print('a') print(a[a[5] ]) end,
  ['1']   = function(...) local a={...} print('b') print(a[a[4] ]) end,
  bye     = function(...) local a={...} print('c') print(a[a[3] ]) end,
  default = function(...) local a={...} print('d') print(a[a[2] ]) end,
  }
local c = sl.case(t)
local z = 'bye'
c.on(z,2,3,4,5,6)
--> 'c'
--> 5

Description

Calling case returns a case closure with one defined method, on. This closure can stand in place of complicated if-elseif code and functions analogously to the C language switch case construct except that it can be called anywhere once defined. The first parameter passed to the on method selects a function from the initial case table and calls it with the remaining parameters passed through. If the selector isn't found among the case table keys, then the default key 'default' is searched for and if found, the associated function is called. If neither the selector value or 'default' is found in the case table, then an error is raised.

Alternative Calling Patterns

Upon Error

See Also