Should I use string.format() instead of Concatenation?

Hello. I always use Concatenations but I recently came across string.format() / :Format()

I see that it does the exact same thing, but which one is the best or is it just preference?

I know that string.format() automatically does tostring() and it supports more datatypes, but im mostly gonna be using it for strings, so which one is the best?

Formatting is the slowest, but it’s type-safe and allows for specific formatting options, for example %d or %a.

String concatenation is better for simple strings, it works well for basic classes and allows for nil values. But, it can worse on the memory usage side.

String interpolation (backticks) is more advanced concatenation. It is more concise and readable, as well as supporting more advanced formatting options.

it all depends on your situation.

Here’s a few quick examples:

  • If you were doing a timer, you would probably use formatting.
local hours = 04
local mins = 05
local secs = 06

local timer = string.format("%d:%d:%d", hours, mins, secs)
  • If you were doing a string with lots of variables needed in it, you would interpolate it.
local str = `{variable1} is good compared to {variable2} but worse than {variable3} and better than {variable4}`
  • If you had a string with only a few variables needed in it, you would concatenate it.
local str = "Player 1 scored "..player1Score.." which is "..difference.." more than Player 2!"

All will automatically convert numbers to strings.

1 Like

Thanks man

30 chaaaaaaaaaaa

1 Like

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