刚开始使用lua的人肯定会不满lua居然没有switch这个语法。
但是熟悉lua的强大特性之后,你会发现其实switch是完全没有必要提供的^.^,因为lua有强大的table和function
例子:
local key = 1
local switch = {
[1] = function()
print("switch:"..1)
end,
[2] = function()
print("switch:"..2)
end,
["test"] = function()
print("switch:test")
end,
}
local fSwitch = switch[key] --switch func
if fSwitch then --key exists
local result = fSwitch() --do func
else --key not found
end
模版如下:
local switch = {
[case1] = function()
--case 1
end,
[case2] = function()
--case 2
end,
}
local fSwitch = switch[key] --switch func
if fSwitch then --key exists
local result = fSwitch() --do func
else --key not found
end
方法:
1、菜单-Preferences-Tools-New Snippet ,sublime自动新建一个文件
2、把代码全部复制进去,然后保存,文件名填 switch.sublime-snippet
<snippet>
<content><![CDATA[local switch = {
[${1:case1}] = function()
${2:--case 1}
end,
[${3:case2}] = function()
${4:--case 2}
end,
}
local fSwitch = switch[${5:key}] --switch func
if fSwitch then --key exists
local result = fSwitch() --do func
else --key not found
end
]]></content>
<tabTrigger>switch</tabTrigger>
<scope>source.lua</scope>
<description>switch-case</description>
</snippet>
方法二:
1、新建文本文档,把复制代码进去,然后保存,文件名写switch.sublime-snippet
2、sublime菜单-Preferences-Browse Packages打开文件夹
3、把刚才保存的switch.sublime-snippet文件放入User目录里面
这样就可以在sublime里面使用了
效果如下