Parts of a Text

Often, you need only a part of a text: the first letter of a name, the year in a date. The method sub (short for substring, a part of a string) gives the part between two positions. The characters of a text are numbered from 1, like the items of a list, and both positions are included:

local word = "sunflower"
print(word:sub(1, 3))
print(word:sub(4, 9))
print(word:sub(4))

This prints:

sun
flower
flower

Without the second position, sub goes to the end of the text. To get one character, give the same position twice: word:sub(1, 1) is "s". Lua has no special type for a single character; it's just a text of length 1.

Positions can also be negative. Then they count from the end: -1 is the last character, -2 the one before it, and so on. That's handy when you know how long the end of a text is, but not how long the whole text is:

local word = "sunflower"
print(word:sub(-1))
print(word:sub(-6))
print(word:sub(1, -7))

This prints:

r
flower
sun

The last line takes everything from the first character to the seventh from the end: the word without its last six characters.

sub never ends with an error. Positions past the end give as much as there is, and when there's nothing between the positions, you get an empty text:

local word = "sunflower"
print(word:sub(5, 100))
print(word:sub(20) .. "|")

This prints:

lower
|

Methods give new texts, so you can call another method straight on the result. This is how you write a word with a capital first letter: take the first character in capitals and join the rest to it:

local name = "bella"
local nice = name:sub(1, 1):upper() .. name:sub(2)
print(nice)

This prints:

Bella

name:sub(1, 1):upper() runs from left to right: first sub gives "b", then upper makes it "B". And this loop goes through all the characters, one at a time:

local word = "hen"
for i = 1, #word do
    print(i, word:sub(i, i))
end

This prints:

1	h
2	e
3	n

Typical mistake: forgetting that the second position is included. word:sub(1, 4) gives four characters, "sunf", not three. And like #, the positions count bytes, so a letter with an accent takes two of them. More on that later in this lesson.

Instructions

Every label ends with the date of the harvest, and a date is always 10 characters long. Take it with sub and a negative position, store it in a variable date, and print Date: 2026-06-14.

The name of the crop is everything before the space: the label without its last 11 characters (the space and the date). Store it in a variable crop, and print it with a capital first letter: Crop: Carrots.

Emma's customers are used to dates in the American order: month, day, year. Take the year, the month and the day from date with sub, and print Harvested: 06/14/2026.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/9