Lua - String Concatenation



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 - Exception while Concatenating Strings

Consider the example shown below −

main.lua

-- define string variables
str1 = "tutorials"
str2 = "point"

-- will throw an error
s = str1 + str2
print(s)

Output

When we run the above code, we will get the following output−

lua: main.lua:6: attempt to perform arithmetic on global 'str1' (a string value)
stack traceback:
	main.lua:6: in main chunk
	[C]: ?

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 - Concatenating Strings

Consider the example shown below −

main.lua

-- define string variables
str1 = "tutorials"
str2 = "point"

-- concatenate strings
s = str1..str2

-- print the concatenated strings
print(s)

Output

When we run the above code, we will get the following output−

tutorialspoint

Example - Concatenating Strings

Consider the example shown below −

main.lua

-- define string variables
message = "Hello, " .. "world!"

-- print message
print(message)

Output

When we run the above code, we will get the following output−

Hello, world!

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

Example - Error while Concatenating Strings

Consider the example shown below −

main.lua

-- define string variables
str1 = "tutorials"
str2 = "point"

-- concatenate str2 to str1
str1 ..= str2

-- print str1
print(str1)

Output

When we run the above code, we will get the following output−

lua: main.lua:6: '=' expected 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 - Concatenating numbers

Consider the example shown below −

main.lua

-- define an array variables
numbers = {}

-- run a loop
for i=1,10 do
   -- initialize the array values
   numbers[i] = i
end

-- concatenate numbers
message = table.concat(numbers)

-- print message
print(message)

Output

When we run the above code, we will get the following output−

12345678910
Advertisements