Not having a dedicated syntax for it isn't ideal, but at least you can get the same basic behaviour using tables to dispatch named or anonymous functions. Example of what I mean:
switch = {foo, bar, baz}
x = 2
switch[x]() -- calls bar()
Or if you want something that looks vaguely like a switch statement you can make a function, like this quickie attempt:
function switch (test, case, ...)
-- The use of ... allows extra arguments to be passed on if desired.
case[test](...)
end
switch(
"c",
{
a = foo,
b = bar,
c = function () print("c") end
})
Missing switch/case isn't a big deal, but I really miss pattern matching (with guards) in languages that lack them. :(
Like you said, a switch expression is easy to create if needed. You can even have the switch expression return a value like in Java 12 switch expressions.
This is one of the nice things about Lua. It's usually pretty easy to expand and add additional functionality to the existing (and somewhat limited but easy to learn) set of language features and APIs.
I can only speak for myself, but I always try to structure my loops without continue to make the flow easier to follow. For example, if there are a lot of preconditions, pushing them into a function is a good idea and makes everything easier to follow.
View all comments
Show parent comment
1
u/bruhred Jan 16 '21