Smaller Conditional Statements

If statements are so big. Learn how to make smaller versions for variables!

by sonicbrennan2

Author Avatar

Conditional statements are very useful. It's very hard to write a game without them. But sometimes, they're just so big! How could you reduce size while keeping usability? Well, lua's logical operators can solve this problem. Here's an example.

This line of code

local store
local burger = "Closed"
local hotdog = "Open"

if burger == "Open" then
    store = "Burger"
elseif hotdog == "Open" then
    store = "Hotdog"
    store = "None"

can be shrunk down into this.

local burger = "Closed"
local hotdog = "Open"

local store = burger == "Open" and "Burger" or
hotdog == "Open" and "Hotdog" or "None"

So how does this work? To explain this, we have to take a look at some of the logical operators in lua. For an example, if you were to put the following code into the command bar, you would get an output of "Burger".

local burger = "Burger"
print(burger and "Burger")

So why is this? Well, when you just have and alongside two values, it could output one of the two values. If value #1 was false, it would have outputted value #1. If value #1 was true, however, it would output value #2.

So, what does the "or" operator have to do with this? Well, "or" is sort of like a reverse "and" operator. If the first value is true, it will return value #1. If it is false, it'll return value #2.

As an example, this

local burger = false
print(burger or "Closed")

would print "Closed". Since "and" will return false if value #1 is either nil or false, that means the "or" operator will take place and return the second value applied to it.

Hopefully this wasn't too confusing, I've never written a tutorial before. Thanks for sticking with me until the end, and I hope this helps you!

View in-game to comment, award, and more!