lua中实现switch以及sublime下自动补全switch语法

来源:互联网 发布:99宿舍网络加速器 编辑:程序博客网 时间:2024/04/29 19:56

刚开始使用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

0 0
原创粉丝点击