Concatenation of strings in Lua programming


Concatenation of strings is the process in which we combine two or more strings with each other, and in most of the programming languages this can be done by making use of the assignment operator.

In Lua, the assignment operator concatenation doesn’t work.

Example

Consider the example shown below −

 Live Demo

str1 = "tutorials"
str2 = "point"
will throw an error
s = str1 + str2
print(s)

Output

input:7: attempt to add a 'string' with a 'string'

Hence, the most straightforward way is to make use of the concatenation keyword which is denoted by .. (two dots)

Let’s consider a few examples of the concatenation keyword in Lua.

Example

Consider the example shown below −

 Live Demo

str1 = "tutorials"
str2 = "point"
s = str1 .. str2
print(s)

Output

tutorialspoint

Example

Consider the example shown below −

 Live Demo

message = "Hello, " .. "world!"
print(message)

Output

Hello, world!

It should be noted that Lua doesn’t allow augmented concatenation.

Example

Consider the example shown below −

 Live Demo

str1 = "tutorials"
str2 = "point"
str1 ..= str2
print(str1)

Output

input:5: syntax error near '..'

It should also be noted that whenever we make use of the concatenation operator, a new string gets created internally and the concatenation is done on that string, and this approach has performance issues when we want to concatenate multiple strings in one string.

Alternate approach is to make use of the table.concat function.

Example

Consider the example shown below −

 Live Demo

numbers = {}
for i=1,10 do
numbers[i] = i
end
message = table.concat(numbers)
print(message)

Output

12345678910

Updated on: 20-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements