2012年2月24日 星期五

Simulate Switch in Lua

因為Lua不知道為啥沒有Switch的流程控制可以使用,Lua製作團隊應該也是被問到煩死了才寫了Lua switch wiki的吧,因為目前沒有涉略很深,就直接用個最簡單的範例吧。

A simple version of a switch statement can be implemented using a table to map the case value to an action. This is very efficient in Lua since tables are hashed by key value which avoids repetitive if <case> then ... elseif ... end statements.
action = {
  [1] = function (x) print(1) end,
  [2] = function (x) z = 5 end,
  ["nop"] = function (x) print(math.random()) end,
  ["my name"] = function (x) print(x) end,
}
Usage (Note, that in the following example you can also pass parameters to the function called) :-
action[case](params)
example: action["my name"](" is tkdstkdstkds");
This is pseudocode for the above:
switch (caseVariable) 
  case 1: print(1)
  case 2: z=5
  case "nop": print(math.random())
  case "my name": print(" is tkdstkdstkds")
end

沒有留言:

張貼留言