切换对象

lua-users home
wiki

面向对象的方式来实现 switch
local function switch_isofcase(val, values)
	local vt = type(values)
	if vt == 'table' then
		for i, v in ipairs(values) do
			if v == val then return true end
		end
		return false
	end
	if vt == 'function' then
		return values(val)
	end
	return (values == val)
end

local function switch_test(switch, val)
	for i, case in ipairs(switch.cases) do
		if switch_isofcase(val, case.value) then
			if case.func then return case.func(val, case.value) end
			return case.ret
		end
	end
	if switch.default_func then
		return switch.default_func(val, 'default')
	end
	return switch.default_ret
end

local function switch_case(switch, value, fn)
	if type(fn) == 'function' then
		table.insert(switch.cases, {value = value, func = fn})
	else
		table.insert(switch.cases, {value = value, ret = fn})
	end
end

local function switch_default(switch, fn)
	if type(fn) == 'function' then
		switch.default_func = fn
	else
		switch.default_ret = fn
	end
end

function switch()
	local s = {}
	s.cases = {}
	s.test = switch_test
	s.case = switch_case
	s.default = switch_default
	return s
end

--- Testing part ---
local fn = function(a, b) print(tostring(a) .. ' in ' .. tostring(b)) end
local casefn = function(a)
	if type(a) == 'number' then
		return (a > 10)
	end
end

local s = switch()
s:case(0, fn)
s:case({1,2,3,4}, fn)
s:case(casefn, fn)
s:case({'banana', 'kiwi', 'coconut'}, fn)
s:case({'banana', 'pineapple', 'coconut'}, fn)
s:default(fn)

s:test(0)
s:test(2)
s:test(5)
s:test(15)
s:test('kiwi')
s:test('banana')
s:test('pineapple')
s:test(nil)

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2012 年 11 月 15 日下午 2:56 GMT (差异)