Numbers and strings
Lua's arithmetic:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * |
add, subtract, multiply | 6 * 7 |
42 |
/ |
divide (always a decimal) | 7 / 2 |
3.5 |
// |
divide, rounding down | 7 // 2 |
3 |
% |
remainder | 7 % 2 |
1 |
^ |
power | 2 ^ 10 |
1024.0 |
The math library has the rest: math.pi, math.floor(3.7) (3), math.max(4, 9), math.sqrt(16), math.random(1, 6).
Strings
local s = "Harare"
print(#s) -- 6: # gives the length
print(string.upper(s)) -- HARARE
print(string.sub(s, 1, 3)) -- Har (positions start at 1 in Lua)
print(s:lower()) -- harare (the same as string.lower(s))
string.format
string.format builds text from a pattern. %s is replaced by a value, %d by a whole number, and %.2f by a number with 2 decimal places:
print(string.format("%s owes $%.2f", "Tino", 7.5)) -- Tino owes $7.50
Your task
Write three functions (a function is local function name(params) ... end; the next lesson covers them properly):
area_of_circle(r)returns pi times r squared.label(name, value)returns e.g."Area: 12.57"(2 decimal places).shout(text)returns the text in capitals followed by!.