14. Working with text — Homework solutions

The .lua solution files are in exercises/14/homework/solutions/.

Problem 1 — Initials

Problem. Print initials like K.R. from first and last names.

How to think about it. A name's first letter is string.sub(name, 1, 1). Join with .. and dots.

Worked solution.

local first = "Keiko"
local last = "Raharja"

print(string.sub(first, 1, 1) .. "." .. string.sub(last, 1, 1) .. ".")

Output:

K.R.

Common mistakes.

  • string.sub(first, 1) (no end) returns the whole name. Use (first, 1, 1).

Problem 2 — Contains

Problem. Print yes or no for whether a sentence holds lua.

How to think about it. string.find returns nil when the word is missing, and nil is falsy, so it drops into an if.

Worked solution.

local sentence = "i am learning lua this year"

if string.find(sentence, "lua") then
    print("yes")
else
    print("no")
end

Common mistakes.

  • Comparing with == true. find returns a number on a match, not true. Let the if test it; non-nil is truthy.

Problem 3 — Censor

Problem. Replace every space with a dash.

Worked solution.

local message = "meet me at noon"
print(string.gsub(message, " ", "-"))

Wait — that prints two things, since gsub also returns a count:

meet-me-at-noon 4

To print just the string, store it:

local message = "meet me at noon"
local dashed = string.gsub(message, " ", "-")
print(dashed)         -- meet-me-at-noon

Common mistakes.

  • Surprise at the trailing number. gsub returns the string and the count; capture it to keep just the string.

Challenge — Last word length

Problem. Print the last three characters with a negative index, and the length with #.

Worked solution.

local word = "programming"

print(string.sub(word, -3))   -- ing
print(#word)                  -- 11

Since -3 counts from the end, this gives the last three letters of any word — no counting.

Common mistakes.

  • string.sub(word, #word - 2) also works, but -3 is shorter and clearer: "three from the end".

Done?

You can now slice, search, and replace text. Part 3's last chapter — Getting input — lets users type values, arriving as strings to slice and check.