Lua provides a number of formatting directives that can be used to insert values into a string. These directives are enclosed in percent signs (%
).
For example, the following code will print the string "The number is 10":
Lua
str = "The number is %d"
num = 10
print(str:format(num))
Use code with caution.
The %d
formatting directive tells Lua to insert an integer value into the string. There are many other formatting directives available, such as %s
for strings, %f
for floats, and %b
for boolean values.
The following table lists some of the most commonly used Lua string formatting directives:
Formatting directiveDescription%d
Inserts an integer value.%s
Inserts a string value.%f
Inserts a floating-point value.%b
Inserts a boolean value.%%
Inserts a literal percent sign.
drive_spreadsheetExport to Sheets
The :format()
method takes a table of values as its argument, and inserts the corresponding values into the string. For example, the following code will print the string "The number is 10 and the name is John":
Lua
str = "The number is %d and the name is %s"
num = 10
name = "John"
print(str:format(num, name))
Use code with caution.
The :format()
method can also be used to insert formatted strings into other strings. For example, the following code will print the string "The number is 10 in hexadecimal is 0x10":
Lua
str = "The number is %d in hexadecimal is %#x"
num = 10
print(str:format(num))
Use code with caution.
The %#x
formatting directive tells Lua to insert the hexadecimal representation of the integer value.
Lua String Formatting Tips
Here are some tips for using Lua string formatting:
Use the
%s
formatting directive to insert strings, even if the string contains only numbers. This will prevent Lua from interpreting the numbers as special characters.Use the
%#x
formatting directive to insert hexadecimal representations of integer values. This will make the numbers easier to read and understand.Use the
%f
formatting directive to insert floating-point values with a specific number of decimal places. This will make the numbers more accurate and precise.Use the
%%
formatting directive to insert a literal percent sign. This is useful if you want to insert a percent sign as part of a string.
Conclusion
Lua string formatting is a powerful tool that can be used to insert values into strings. By following the tips in this blog post, you can use string formatting to create clear and concise strings that are easy to read and understand.