Lua, lesson 3
Standard input (stdin) is the text fed into your program, such as the Input box when you run
code here. Lua reads it with io.read.
io.read takes a format that says what to read:
| Call | Reads | Gives you |
|---|---|---|
io.read("l") | the next line, without the line break | a string |
io.read("n") | the next number, skipping spaces and new lines | a number |
io.read("a") | everything that is left | a string |
io.read() with no argument is the same as . When there is nothing left to
read, and return ( also returns if the text is not a number).
2 exercises to try what you just read.
io.read("l")"l""n"nil"n"nilio.read("n") is the quickest way to get numbers. It skips whitespace, so it works whether
the numbers are on separate lines or on the same line separated by spaces:
You can also read several at once: local a, b = io.read("n", "n").
If you already have a line of text, tonumber converts it. It returns nil when the text
isn't a number, which you can test for later:
A tricky point: if you mix formats, io.read("n") stops right after the number and leaves
the line break unread. A following io.read("l") then returns an empty string. Stick to one
style per input when you can.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 7 * 2 | 14 |
/ | division, always a float | 7 / 2 | 3.5 |
// | floor division | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
^ | power, always a float | 2 ^ 10 | 1024.0 |
Lua keeps track of whether a number is an integer or a float. Integer +, -, *, //
and % give integers, but / and ^ always give floats. That is why 10 / 2 prints 5.0.
When you want a whole-number answer, use //.
// rounds toward minus infinity, so -7 // 2 is -4, and % is defined to match it.
The math library has the rest: math.floor, math.ceil, math.abs, math.max,
math.min, math.sqrt, and math.tointeger to turn a float like 5.0 into the integer 5.
string.format builds a string from a template, like printf in C. %d is an integer,
%s a string, %.2f a number with two decimals:
A group of friends shares a pizza. Read the number of slices on the first line and the number of friends on the second line (always at least 1). Everyone gets the same whole number of slices, and the rest stays in the box. Print:
Sample input:
Sample output:
Read a temperature in Celsius as a line of text (it may have a decimal point) and print it in
Fahrenheit with exactly one decimal place. The formula is F = C * 9 / 5 + 32.
Sample input:
Sample output:
Print the Celsius value exactly as it was typed.
local name = io.read("l")
print("Hello, " .. name .. "!")local a = io.read("n")
local b = io.read("n")
print(a + b)local price = tonumber(io.read("l"))print(string.format("Average: %.2f", 10 / 3)) -- Average: 3.33Each friend gets <n> slices
Leftover: <m>10
3Each friend gets 3 slices
Leftover: 121.521.5 C = 70.7 F