码迷,mamicode.com
首页 > 其他好文 > 详细

转载:lua中switch

时间:2017-05-24 19:44:54      阅读:521      评论:0      收藏:0      [点我收藏+]

标签:--   特性   use   rda   key   exists   trigger   例子   too   

刚开始使用lua的人肯定会不满lua居然没有switch这个语法。

 

但是熟悉lua的强大特性之后,你会发现其实switch是完全没有必要提供的^.^,因为lua有强大的table和function

 

例子:

 

[plain] view plain copy
 
  1. local key = 1  
  2. local switch = {  
  3.     [1] = function()  
  4.         print("switch:"..1)  
  5.     end,  
  6.     [2] = function()  
  7.         print("switch:"..2)  
  8.     end,  
  9.     ["test"] = function()  
  10.         print("switch:test")  
  11.     end,  
  12. }  
  13.   
  14. local fSwitch = switch[key] --switch func  
  15.   
  16. if fSwitch then --key exists  
  17.     local result = fSwitch() --do func  
  18. else --key not found  
  19.   
  20. end  

 

模版如下:

 

[plain] view plain copy
 
  1. local switch = {  
  2.     [case1] = function()  
  3.         --case 1  
  4.     end,  
  5.     [case2] = function()  
  6.         --case 2  
  7.     end,  
  8. }  
  9.   
  10. local fSwitch = switch[key] --switch func  
  11.   
  12. if fSwitch then --key exists  
  13.     local result = fSwitch() --do func  
  14. else --key not found  
  15.   
  16. end  

 

 

为sublime增加switch自动补全

方法:

1、菜单-Preferences-Tools-New Snippet ,sublime自动新建一个文件

2、把代码全部复制进去,然后保存,文件名填 switch.sublime-snippet

 

[plain] view plain copy
 
  1. <snippet>  
  2.     <content><![CDATA[local switch = {  
  3.     [${1:case1}] = function()  
  4.         ${2:--case 1}  
  5.     end,  
  6.     [${3:case2}] = function()  
  7.         ${4:--case 2}  
  8.     end,  
  9. }  
  10.   
  11. local fSwitch = switch[${5:key}] --switch func  
  12.   
  13. if fSwitch then --key exists  
  14.     local result = fSwitch() --do func  
  15. else --key not found  
  16.   
  17. end  
  18. ]]></content>  
  19.     <tabTrigger>switch</tabTrigger>  
  20.     <scope>source.lua</scope>  
  21.     <description>switch-case</description>  
  22. </snippet>  



 

方法二:

1、新建文本文档,把复制代码进去,然后保存,文件名写switch.sublime-snippet

2、sublime菜单-Preferences-Browse Packages打开文件夹

3、把刚才保存的switch.sublime-snippet文件放入User目录里面

这样就可以在sublime里面使用了

 

效果如下

技术分享

技术分享

 

 

from: http://blog.csdn.NET/a82239946/article/details/42490405

转载:lua中switch

标签:--   特性   use   rda   key   exists   trigger   例子   too   

原文地址:http://www.cnblogs.com/ebchange/p/6900616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!