Menu
CoddyTech

Conditional Expressions

Lesson 6 of 29 in Coddy's Lua for Luau Developers course.

Luau can place a conditional expression where a value is needed. Lua 5.1 uses if, elseif and else statements ending in end. Move the decision into those branches, assigning a local or returning directly from a function. Keep branch order and inclusive boundaries unchanged. A threshold of zero is easy to break by replacing >= with >. Short-circuit operators remain available for conditions in both languages, but they do not provide a universal conditional-expression replacement. The exercise classifies a temperature, so test the transition points as carefully as ordinary values.

Luau

local n = 0
local label = if n < 0 then "negative" elseif n == 0 then "zero" else "positive"
print(label)

Lua 5.1

local n = 0
local label
if n < 0 then label = "negative"
elseif n == 0 then label = "zero"
else label = "positive" end
print(label)

Porting trap

An if expression has no trailing end in Luau. The Lua statement needs end; removing only the assignment is not enough.

challenge icon

Challenge

Easy

Input is an integer temperature. Return cold below zero, mild from zero through 20, and hot above 20.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Luau Developers

Practice on your own: Online Lua compiler