typestar

if and elseif in Lua

Blocks close with end; and/or double as a value picker.

-- Blocks close with end; elseif chains without extra nesting.
local torchlight = 3

if torchlight > 6 then
  print("The hall is bright")
elseif torchlight > 2 then
  print("Shadows crowd the corners")
else
  print("Total darkness")
end

-- and/or short-circuit; the a and b or c idiom picks a value.
local hp = 4
local status = hp > 10 and "steady" or "limping"
print("Status: " .. status)
if hp < 5 then print("Find a campfire soon") end

How it works

  1. if/elseif/else chain without extra nesting.
  2. and/or short-circuit; only nil and false are falsy.
  3. cond and a or b is Lua's ternary — safe while a is truthy.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
433
Tokens
74
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →

if and elseif in other languages