In computer programming, string interpolation defines the process where string literals are evaluated with one or more variables/placeholders.
Let's say you're coding a game, and you need to concatenate multiple variables and strings into one message for your players. Usually, and unfortunately, most people would have to do this:
local message = "Hello! You have %s coins."
print(string.format(message, 7))
output: "Hello! You have 7 coins.
While it does work as it's intended, the main issue is optimization, and usability. We want to try and make the same function as above, but we want to:
Our solution is by using Luau's implementation of string interpolation. If you've ever used a language like JavaScript, it's very similar to it's implementation. To use string interpolation, all you have to do is:
local value = 7
print(`Hello! You have {value} coins.`)
output: "Hello! You have 7 coins.
"
You can also include multiple arguments in the same string as you can with string.format():
local CoinValue = 7
local levelValue = 5
print(`Hello! You have {CoinValue} coins, and you are level {levelValue}!`)
output: "Hello! You have 7 coins, and you are level 5!"
A very helpful feature that string interpolation includes is that it allows anyone to code in functions directly into string literals, which can be very helpful for certain actions that require them. Here's an example of that in action:
local Players = game:GetPlayers()
print(`Currently, the players in the server are {table.concat(Players, ", ")}.`)
We can also interpolate strings using the __tostring metamethod and metatables. This is also just as helpful as putting built-in functions into strings, such at this example:
local coins = setmetatable({userBalance = 320}, {
__tostring = function(self)
return "$" .. tostring(self.value)
end
})
print(`You have {coins}.`)
output: "You have $320."