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, }
action[case](params)
example: action["my name"](" is tkdstkdstkds");
switch (caseVariable) case 1: print(1) case 2: z=5 case "nop": print(math.random()) case "my name": print(" is tkdstkdstkds") end
沒有留言:
張貼留言