Lua奇技淫巧之二——给Lua添加switch

Lua | 2019-08-28 17:35:20 | 阅读 296 次 | 评论(0)

Lua没有switch语句,我们就给它加一个:

一、简单的switch:

function switch(SwitchVal)
	return function(SwitchTable)
		local ReFunc = SwitchTable[SwitchVal]
		if type(ReFunc) ~= "function" then
			ReFunc = SwitchTable[ReFunc] or SwitchTable.default
		end
		return ReFunc and ReFunc()
	end
end
优点是实现简单,缺点是分支只对单个标签有效,如果一个分支对应若干个标签,写起来就比较麻烦,请看例子:
t = {1,2,3,"1","2","3","one","two","three","default"}
one = "one"
for _, i in ipairs(t) do
	switch(i){
		[1] = function()
			print(1)
		end,
		["2"] = function()
			print('"2"')
		end,
		["1"] = 1,    --多个标签对应一个分支的写法
		["two"] = "2",
		default = function()
			print("default")
		end,
	}
end
二、复杂点的switch:
function switch(SwitchVal)
	return function(SwitchTable)
		local ReFunc = SwitchTable.default
		for _, v in ipairs(SwitchTable) do
			if type(v) == "table" then
				for _, vv in ipairs(v) do
					if vv == SwitchVal then
						ReFunc = v[#v]
						break
					end
				end
			end
		end
		return ReFunc and ReFunc()
	end
end

这个改进了上面那个的缺点,标签还可以使用“default”,和switch的default不冲突。请看例子:

t = {1,2,3,"1","2","3","one","two","three","default"}
one = "one"
for _, i in ipairs(t) do
	switch(i){
		{1,"1",one,		function()
			print(1)
		end},
		{2,"2","two",	function()
			print(2)
		end},
		{"default",		function()
			print("default")
		end},
		default = function()
			print(0)
		end,
	}
end


文章评论,共0条
游客请输入验证码
浏览11804次