What are String Format's and how would I use them


So I’m asking what are String Formats, and how would I use them,

The Documentation, and on script, is confusing to me, and I was wondering if It can be simplified?



string.format is a way to create a string with variables to text. You may have done something like this using the concatenation operator (the two dots)

print("Hello " .. player.Name .. "!")

You could also use string.format to concatenate multiple variables, or numbers.

print(string.format("Hello %s!", player.Name)) -- %s is replaced with the next argument

print(string.format("Hello %s! Your user id is %d. and your x position is %f.", player.Name, player.UserId, character.Position.x))
-- formatters '%' are replaced from left to right with the variables in the same order

Use %s for strings like player.Name, %d for integer numbers (no decimal place), and %f for decimal numbers.

If you have seen printf in the programming language C, this behaves much like that function. In lua I would not worry about using this for optimizations or replacing your concatenated strings with string.format.


I guess this will do, it Isn’t really helpful and is still confusing, but I’ll take it


It is a confusing function, I’ll go over it again in more succinct sections. What other questions do you have?

When to use string.format?

It is totally a stylistic choice over concatenation. It may be helpful when concatenating multiple numbers by using %d or %f. If you are having performance concerns over concatenation it is best to try removing or reducing concatenations first before using this function as a replacement.

How to use string.format

string.format takes a string and inserts other arguments into the supplied string.

To demonstrate the number of arguments, this example will result in greeting being “Hello John Doe!” For every %s a argument must be added, and the %s are replaced in the same order.

local greeting = string.format("Hello %s %s!", "John", "Doe")
                                         ^^-- Doe
                                      ^^-- John
print(greeting) -- Hello John Doe!

To demonstrate the type of sentinels, the three most used are

  • %s for string (“Hello”)
  • %d for integer (123)
  • %f for float (12.345)

We have already seen strings in use with %s, here is an example using integers with %d.

print(string.format("player score: %d pts"), 100) -- player score: 100 pts

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.