1.实现switch 仅仅是为了代码的可读性 和 减少代码量。
由于项目的不同可能会用switch 比较适合的逻辑,之前一直没遇到过,直到我去到一家新公司。
可恶的 if 嵌套 switch 嵌套 可恶心死我了。
新的工作,结构体都给你定好了。改是没可能改的,又是用的c++ 所以想到 lua 是否可以避免这种事情,lua 可以很简单的就解决了 但是c++ 解决这个问题好像真的有点难,反正我是想不到。
嵌套switch c++ 如果这样实现,估计得写一个模板,模板参数每次都得 定义新得函数指针类型参数,更麻烦了。
1.第一种单层次switch
local ifFunction = require("ifFunction")
local switch function(expression, body, ...)
local code = body[expression]
if not code then
local def = body.default
if def then
return def(...)
end
else
repeat
if ifFunction(code) then
return code(...)
else
code = body[code]
end
until not code
end
end
---使用例子
switch("c",{
a = "c",
b = "c",
c = function()
print("case c")
end,
default = function()
print("default")
end
})
注意:body 避免每次都创建新的table 和函数 建议做(上值或者类成员),将需要的参数进去,可以避免使用闭包 不在意效率就忽略
2.第二种嵌套switch
local clear = require("table.clear")
local clone = require("table.clone")
local ifTable = require("ifTable")
local ifFunction = require("ifFunction")
local map = {}
local function tconcat(nbody)
clear(map)
for t, code in pairs(nbody) do
if ifFunction(code) then
if ifTable(t) then
map[table.concat(t)] = code
else
---default
map[t] = code
end
else
---point
map[table.concat(t)] = table.concat(code)
end
end
clone(map, nbody)
return nbody
end
local arg = {}
local map = {}
local function tswitch(param, nargs, nbody, ...)
---构建数组
clear(arg)
for _, k in ipairs(nargs) do
local v = param[k]
assert(nil ~= v)
table.insert(arg, v)
end
---语法缓存
if not map[nbody] then
map[tconcat(nbody)] = true
end
local argv = table.concat(arg)
local code = nbody[argv]
if not code then
---调用函数
local def = nbody.default
if def then
return def(...)
end
end
---找到分支
repeat
if ifFunction(code) then
return code(...)
end
code = nbody[code]
until not code
end
local param = {
a = 1,
b = 2,
c = 4,
}
local nargs = {
"a", "b", "c"
}
local nbody = {
[{ 1, 2, 3 }] = function(param)
print("123")
end,
[{ 1, 2, 4 }] = function(param)
print("124")
end,
[{ 1, 2, 5 }] = { 1, 2, 3 },
default = function(param)
print("default")
end,
}
tswitch(param, nargs, nbody, param)
注意:同上+tconcat:只是将body tableKey 转换成字符串 避免遍历比对tableKey