Cocos2d-x trip _ 39] simulate a switch in LUA
This is actually not difficult, but a friend told me that he encountered the question "Please use lua to simulate Switch" during the interview ...... I think of sharing my previous articles ......
The code is simple:
_ G. switch = _ G. switch or {} _ G. switch. switch_retriable = {_ index = function (t, k) if rawget (t, "default") then return rawget (t, "default") else return function () end ,__ resumable = "do not change the resumable"} function _ G. switch: create () local switch ={} setretriable (switch, _ G. switch. SWITCH_METATABLE) return switchend
Test code:
Local switch = Switch: create () -- create a table as the switch function switch [1] = function () -- set the function print ("switch 1") for each case of the switch ") endswitch [2] = function () print ("switch 2") endswitch [3] = function () print ("switch 3") endswitch [4] = function () print ("switch 4") endswitch ["default"] = function () print ("switch default") endswitch [1] () -- use the value of case as the key to call the method in table to simulate switch [4] () switch [3] () switch [10] () switch ["default"] = nil -- remove the default function switch [11] () -- this row will not have any output
Output result:
[LUA-print] switch 1
[LUA-print] switch 4
[LUA-print] switch 3
[LUA-print] switch default
(The last switch [11] () calls the system default function without output content)