Lesson 2 of 8 · 7 min

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):

  1. area_of_circle(r) returns pi times r squared.
  2. label(name, value) returns e.g. "Area: 12.57" (2 decimal places).
  3. shout(text) returns the text in capitals followed by !.
main.lua
local function area_of_circle(r)
end

local function label(name, value)
end

local function shout(text)
end

print(label("Area", area_of_circle(2)))
print(shout("lua is fun"))

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…