String Interpolation

Better concatenation just added!

by kurtfan5468

Author Avatar

What is String Interpolation?

In computer programming, string interpolation defines the process where string literals are evaluated with one or more variables/placeholders.

Defining the Problem

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:

  1. Make it more readable.
  2. Let it be modular, so we can change whatever we want if we have to later on if we need to.
  3. Remove the limitations that string.format() has with generic string functions.

The Solution to the Problem

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!"

Embedding Built-In Functions into Strings

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, ", ")}.`)

Interpolation with __tostring

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)

print(`You have {coins}.`)

output: "You have $320."

View in-game to comment, award, and more!