How to print a formatted string in Lua

Overview

Formatted strings contain string formatting syntax, which saves as a placeholder for a string value, and it will eventually be replaced during execution by an actual string.

In Lua, the following are the available string formatting syntax or string literals for different datatypes:

  • %s: This serves as a placeholder for string values in a formatted string.
  • %d: This will stand in for integer numbers.
  • %f: This is the string literal for float values.

Formatted string in Lua

Different programming languages have their method of printing formatted strings. In Lua, a method known as string.format() is used in printing a formatted string.

The string.format() method

The string.format() method is used in printing a formatted string to the screen. It interprets the string literals in the provided string and replaces them with the appropriate value.

Syntax

string.format(formattedString,value1...valueN)

Parameters

The method receives the following parameters:

  • formattedString: This string contains the string literals that actual values would replace during execution.

  • value1,...valueN: The value parameter is the variable whose actual value will be inserted at the point where the formatting string literal will be found. The arrangement of these values must correspond with the arrangement of the string literals in the formatted string. N indicates that the value can be as much as you want.

Return value

The value returned is the formatted string with the string literals all replaced by actual values.

Code example

value1 = "make it count"
value2 = "all depends on you"
value3 = " seconds in all "
value4 = 86400
formatted = "The saying goes:\ntoday has %d %s and how it goes %s:\ndo %s"
print(string.format(formatted ,value4,value3,value2,value1))

Explanation

Here is a line-by-line explanation of the above code:

  • Lines 1–4: We declare variables.
  • Line 6: We declared a string named formatted and assigned it the value with all required formatting syntax.
  • Line 7: We print a formatted string formatted declared on line 6 using the string.format() method.

Free Resources