Implementing a switch statement in Lua

From time to time, the lack of a switch statement in Lua [1] comes up on the Lua mailing list [2].

Obligatory Sidebar Links

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 [9], 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.

[1] http://www.lua.org/

[2] http://www.lua.org/lua-l.html

[3] http://lua-users.org/lists/lua-l/2004-09/msg00012.html

[4] http://lua-users.org/lists/lua-l/2005-04/msg00099.html

[5] http://lua-users.org/lists/lua-l/2007-11/msg00099.html

[6] http://lua-users.org/lists/lua-l/2013-11/msg00518.html

[7] http://lua-users.org/lists/lua-l/2014-05/msg00199.html

[8] http://lua-users.org/lists/lua-l/2015-08/msg00156.html

[9] http://lua-users.org/wiki/SwitchStatement

Gemini Mention this post

Contact the author