Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

What would be the best Lua equivalent of a Switch statement?

Asked by
Necrorave 560 Moderation Voter
9 years ago

I have looked into a bit about Switch statements and realized that Lua does not support such statements.

What is a switch statement?

--Note, this will not work in Lua
switch (x)
{
    case true:
        print("X is true")
        break

    case false:
        print("X is false")
        break
}

I was wondering, from your experience, what the best way to recreate this?

I have seen a lot of people using nested conditional statements instead, but I want to know if that is the most effective way to handle this.

Thanks

3 answers

Log in to vote
3
Answered by
Unclear 1776 Moderation Voter
9 years ago

I have looked into a bit about Switch statements and realized that Lua does not support such statements.

Note: I use switch statements regularly in other programming languages, and the opinion below is after careful consideration for the pros and cons of both the switch statement and whether it belongs in the context of Lua.

When I write code in Lua, I don't write code as if I want to write in C, Python, Java, JavaScript, Ruby, etc. You should avoid implementing features that a language lacks over another language. Most of the time, your choice is unjustified and silly.

Anyhow, switch statements are probably most notable for the following characteristics:

1) only compare once

2) only compares against constant-expressions

Some nearly irrelevant characteristics are:

3) are prettier (to some people)

4) are fewer characters

5) are faster (sometimes, but this is often due to compiler optimizations)

In all honesty...

1 & 2) to replicate switch comparison behavior you're probably going to turn to using a dictionary-style table (though this doesn't truly replicate switch behavior either). This is overcomplicating your code just to get some pretty styling rather than actually replicating switch behavior. If you are not actually replicating switch behavior, there is no reason to try doing it. You'll only make your code more complicated for both yourself, anyone who reads your code, and the Lua interpreter.

3) pretty code is not always good code.

4) this is a ridiculous reason to want to implement switch behavior.

5) your implementation is probably slower anyway.

Please do not use a switch statement imitation in Lua. You can do it for curiosity's sake, but it is really useless in this context and really not worth your time.

0
Thanks a lot, I use them very often myself. Although, I never really had a reason to do it on Roblox. I just figured it would be something worth learning. Thanks for the answer. Necrorave 560 — 9y
Ad
Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

A switch case statement essentially just lets you flip between a bunch of mutually exclusive branches. (A poor behavior in most languages is the "pass through"...)

There are two basic patterns you could use to accomplish this in Lua:

Elseif

You don't need nested if statements, because you can use elseif. This looks almost like switch, except that you have repeat x == (or whatever your condition) in each one:

if day == "Monday" then
    print(":(")
elseif day == "Tuesday" then
    print(":|")
elseif day == "Wednesday" then
    print(":|")
elseif day == "Friday" then
    print(":)")
elseif day == "Saturday" then
    print(":)")
else -- (Default)
    print("...")
end

Definitely more verbose than switch case in most languages, but also not as bad as having nested ifs.

Dictionaries

If the things you're looking up are singletons or primitives, then you can use a dictionary:

local Reactions = {
    Monday = ":("
    Tuesday = ":|"
    Wednesday = ":|"
    Friday = ":)"
    Saturday = ":)"
}

....

print( Reactions[day] or "..." )
Log in to vote
0
Answered by 9 years ago

One way I've done this is like so:

local switch = function(Condition,Cases,Default)
    if Cases[Condition] then
        Cases[Condition](Condition)
    else
        Default(Condition)
    end
end

Condition is the condition to check, Cases is a list of cases to check with, formatted as {false = function()...end, yes = function()...end}, and Default is the default case if none match.

0
Not sure I understand what is going on here... If you could walk me through it a little more that would be swell. Thanks. Necrorave 560 — 9y
0
Like what YonaJune said, it's not really worth your time. But anyway, you provide the cases as functions in `Cases`. It checks if there is a case matching the condition, and if so, executes it. If not, it executes the default case. TickerOfTime 70 — 9y

Answer this question