You could make it take into account default though, it’s very similar to your code already except for ditching the unnecessary metatable and not having a condition for default which would be trivial to add. I’m not particularly sure why the metatable is there either since you don’t actually use any of the benefits of the metatable except for disguising a table as a function. Why…?
I’ve been learning C# as another language, and I was kind of annoyed that Lua didn’t have switches, as I found them to be very simple and useful. Pretty good module!
What is the justification for a metatable over a regular function? I don’t get it. Surely this could just be written as…
return function(item, cases)
local value = cases[item] or cases.default
if value ~= nil then
return type(value) == "function" and value() or value
end
end
… right? I genuinely see no reason for the weird metatable, unless I am missing something.
You are correct, though the if value ~= nil then … end lines are unnecessary because keeping and removing them will have the same result.
The differences in time it takes to run, and memory usage is negligible, though my knowledge with Assembly makes me think otherwise, however the differences become negligible during benchmarking.
That being said, regardless of what benchmarking says, the metatable is unnecessary.
Still, though, best implementation of switch statements I’ve seen so far. Won’t personally use this but I am sure others will find use in it.
There’s also this way, which is a bit unnecessary, but it’s interesting.
local function switch(condition)
return function(results)
local res = results[condition] or results['default']
return (type(res) == 'function') and res() or res
end
end
And then:
local animal = 'dog'
local result = switch(animal) {
['cat'] = function()
print('Meow')
return 'This is a cat'
end,
['dog'] = function()
print('Woof')
return 'This is a dog'
end,
['default'] = 'Not a valid animal'
}
print(result)