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.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.
string.format()
methodThe 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.
string.format(formattedString,value1...valueN)
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.
The value returned is the formatted string with the string literals all replaced by actual values.
value1 = "make it count"value2 = "all depends on you"value3 = " seconds in all "value4 = 86400formatted = "The saying goes:\ntoday has %d %s and how it goes %s:\ndo %s"print(string.format(formatted ,value4,value3,value2,value1))
Here is a line-by-line explanation of the above code:
formatted
and assigned it the value with all required formatting syntax.formatted
declared on line 6 using the string.format()
method.