Learn Lua · Strings · Lesson 2 of 3

Formatting text

string.format builds text from a pattern. Each % code is replaced by the next value: %s for text, %d for a whole number and %.2f for a number with two decimal places:

LUA
string.format("%s: %d copies", "Flyer", 250)  --> "Flyer: 250 copies"
string.format("%.2f", 7.5)                    --> "7.50"

A number before the letter sets a width, and a 0 pads with zeros:

LUA
string.format("%05d", 42)  --> "00042"

What your code receives

Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.

LUA
input = { total = 64.9, number = 42, product = "Flyer", copies = 250 }

Steps

  1. Return amount: input.total with exactly two decimal places, such as "7.50".
  2. Add reference: input.number padded with zeros to six digits, such as "001042".
  3. Add label: the product and copies like "Flyer: 250 copies".
Show a hint

Use one string.format for each field. For the reference, the width is the number of digits you want, with a 0 in front so the gap fills with zeros.