Interpolating a string

Lua:
Interpolating a string

How to:

In Lua, use .. for concatenation or string.format for interpolation. Example:

local name = "Ada"
local greeting = "Hello, " .. name .. "!"
print(greeting) -- Output: Hello, Ada!

local age = 30
local bio = string.format("%s is %d years old.", name, age)
print(bio) -- Output: Ada is 30 years old.

Deep Dive

Historically, Lua lacked built-in string interpolation, unlike some other languages (e.g., Ruby, Python). Concatenation with .. was the go-to way. Lua 5.3 introduced string.format for a cleaner approach, similar to C’s printf. Alternatives: Besides using the .. operator or string.format, you can also write a custom interpolation function that uses gsub for pattern matching. But why complicate things? Use built-in tools for maintainability. Implementation Details: Be aware that frequent string concatenation can lead to performance issues. string.format is helpful when you need formatting control, like specifying number precision or padding.

See Also