switch
Syntax:
(switch condition function^2 [function])
Argument List:
condition: a condition which must be fulfilled in order to execute a subsequent function
function: a function that gets invoked if the previous condition is met (i.e. evaluating to non-Nil)
optional function: a function which will be executed if all conditions evaluate to Nil, i.e. if all of them are 'false'.
Returns:
Whatever the function that eventually gets invoked, returns.
Category:
Control Structure
Description:
Allows branching of the code by more than 1 condition. For just 1 condition, 'if' is good enough. It just evaluates all the conditions (every even argument; odd arguments are corresponding functions) in left to right order, until the first one that evaluates to non-Nil. It then invokes the corresponding function, which is the argument that directly follows that condition. If all the conditions evaluate as Nil, then the last, optional function is invoked.
Example:
Code: Select all
(setq num 3)
(switch
(eq num 1)
(objSendMessage gPlayerShip Nil "num = 1")
(eq num 2)
(objSendMessage gPlayerShip Nil "num = 2")
(eq num 3)
(objSendMessage gPlayerShip Nil "num = 3")
(eq num 4)
(objSendMessage gPlayerShip Nil "num = 4")
(objSendMessage gPlayerShip Nil "num not in (1,2,3,4)")
)
Useful for various multiple choices in the code. In could be replaced by series of 'if's but then there would be even more parentheses than now. Also, it's interesting to notice that there probably isn't any real difference between 'conditions', 'functions' and 'optional function': these are legal switch function examples:
(switch 1 11 2 12 3 13 4 14 5 15) -> evaluates as 11
(switch Nil 11 Nil 12 3 13 4 14 5) -> evaluates as 13
(switch Nil 11 Nil 12 Nil 13 Nil 14 5) -> evaluates as 5
So it just takes a list of arguments, evaluates the first one, if it's non-Nil, evaluates the second and retuns whatever it is. If the first argument is Nil, skips the second and evaluates the third; if that one is non-Nil, evaluates the fourth and returns, etc. The 'optional function' might also be considered just another condition, which doesn't have a following argument, thus (switch Nil 11 Nil 12 3) evaluates as 3. It really is simple when you look at it this way.