Cocos2d-x trip _ 39] simulate a switch in LUA

Source: Internet
Author: User

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)



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.