Lua, lesson 4
Programs need to choose: charge shipping only on small orders, warn when a battery is low.
In Lua you make that choice with if.
The condition goes between if and then. The block ends with end. For more than two
cases, add elseif branches (one word, no space):
Lua checks the conditions from top to bottom and runs only the first branch that matches.
Both elseif and else are optional, but there is always exactly one end.
| Operator | Meaning |
|---|
2 exercises to try what you just read.
== | equal |
~= | not equal (a tilde, not !=) |
< <= > >= | ordering |
Comparisons give true or false. Be careful: Lua never converts between strings and numbers
when comparing. "10" == 10 is false, and "10" < 5 is an error. Convert input with
tonumber (or read it with io.read("n")) before comparing.
Lua spells the boolean operators as words:
and and or short-circuit: if the left side decides the answer, the right side is not
evaluated.
This is the rule that surprises people coming from other languages: in Lua, only false and
nil are false. Everything else is true, including 0 and the empty string "".
and and or don't just return true or false; they return one of their operands. a or b
gives a if it is true, otherwise b. That gives you two handy idioms:
The second one works as long as the middle value isn't false or nil. Here 0 is fine,
because 0 is true in Lua.
Read a whole-number temperature in Celsius and print one word describing it:
freezingcoldmildhotSample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap
years only if they are also divisible by 400. Read a year and print either
<year> is a leap year or <year> is not a leap year.
Sample input:
Sample output:
local battery = 12
if battery < 20 then
print("Low battery!")
print("Plug in soon.")
else
print("Battery OK")
endif score >= 90 then
print("A")
elseif score >= 80 then
print("B")
else
print("C or below")
endif age >= 13 and age <= 19 then print("teen") end
if day == "Sat" or day == "Sun" then print("weekend") end
if not is_open then print("closed") endif 0 then print("0 is true in Lua!") endlocal name = input_name or "guest" -- default value when input_name is nil
local fee = (total >= 50) and 0 or 5 -- like a one-line if/else18mild20242024 is a leap year