Switch Object

lua-users home
wiki

An object oriented approach to 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)

RecentChanges · preferences
edit · history
Last edited November 15, 2012 2:56 pm GMT (diff)