I would like to know if there is a alternative to using a normal if statement in lua. For example, in java there are switch statements but I cant seem to find that in Lua
Asked
Active
Viewed 1,247 times
-1
-
1What is wrong with `if` statements? – Scott Hunter Apr 21 '22 at 12:12
-
1Can always do `while condition do print"yay" do break end end` instead of `if condition do print"yay" end` :P – Luatic Apr 21 '22 at 12:20
-
There isnt anything wrong with the if statements, I am just interested in furthering my lua knowledge :) – Vish10 Apr 21 '22 at 12:24
3 Answers
2
Lua lacks a C-style switch statement.
A simple version of a switch statement can be implemented using a table to map the case value to an action. This is very efficient in Lua since tables are hashed by key value which avoids repetitive if then ... elseif ... end statements.
action = {
[1] = function (x) print(1) end,
[2] = function (x) z = 5 end,
["nop"] = function (x) print(math.random()) end,
["my name"] = function (x) print("fred") end,
}

Reza A. Moghadam
- 21
- 3
-
2All your functions don't need `x`. Also please attribute this to http://lua-users.org/wiki/SwitchStatement. – Luatic Apr 21 '22 at 12:19
2
The frequently used pattern
local var; if condition then var = x else var = y end
can be shortened using an and
-or
"ternary" substitute if x
is truthy:
local var = condition and x or y

Luatic
- 8,513
- 2
- 13
- 34
0
if test == nil or test == false then return 0xBADEAFFE else return test end
Can be shorten up to...
return test or 0xBADEAFFEE
This works even where you dont can do: if ... then ... else ... end
Like in a function...
print(test or 0xBADEAFFE)
-- Output: 3135156222
...or fallback to a default if an argument is ommited...
function check(test)
local test = test or 0xBADEAFFE
return test
end
print(check())
-- Returns: 3135156222

koyaanisqatsi
- 2,585
- 2
- 8
- 15