Friday, August 14, 2015
Implementing a switch statement in Lua
From time to time,
the lack of a switch
statement in Lua comes up on the Lua mailing list.
Over the years I've been using Lua,
I only missed switch
when I first started,
as I was trying to write Lua like it was C.
But over time,
I've come to realize that a switch
statement isn't really needed that often,
not with first class functions.
A minimal implementation is just three lines of code:
function switch(key,case,otherwise) return (key[case] or otherwise or function() return nil end)(case,key) end
Which allows you to do something like:
switch(i, { [true] = function() print("i is true") end, [10] = function() print("i is is 10") end, ['foobar'] = function() print("i is 'foobar') end, [print] = function() prnit("i is the function print()") end, }, function() print("i is not something I recognize") end )
It's about the same syntactical overhead as the switch
statement in C or Java.
The reason I pass the case
table to each function is to allow a C-style “fallthrough” case,
like:
switch(i, { [1] = function() flag = true end, [2] = function(case) case[1]() print(flag) end, }, function() print "Unknown!" end )
Notice how when i
is 2,
we execute the case for then i
is 1,
and print flag
(also,
the indices are superfluous—I just included them to be explicit).
Also note how this can be used in an expression context—something that can not be said for C (or C++, or Java or … ).
Is this the best solution? Hard to say. It is the shortest, but it isn't that tolerant of of errors. But because it's so easy to implement, it can be adapted to just about any style you want.