Lua has a handful of operators which can perform a variety of operations. These operators widely cover:
In this shot we will look at the concatenation operation.
The concatenation operation involves an operator which links two chunks of strings as one word.
The string concatenation operator used in Lua is denoted by two dots ('..')
. In a case where the operands at the left and right-hand sides of the operator are not strings but numbers, or a combination of numbers and strings, then the numbers will be converted to strings in a non-specified format. Otherwise, the _concat
metamethod will be tried by Lua in order to try and concatenate the chunks.
For example, if A = "The first chunk"
and B = "the second chunk"
are to be concatenated, we simply do
A..B
, and the outcome will be: "The first chunk the second chunk"
.
In the code snippet below, we will see a few concatenation operations.
--declare variablesstringVal1 = "Educative Edpresso "stringVal2 = "A revered platform "stringVal3 = "For dev/tech byte size shots, "stringVal4 = "Enjoy your reading"--concatenate the earlier declared chunks and print itprint(stringVal1..stringVal2)--concatenate the earlier declared chunks and print itprint(stringVal3..stringVal4)--concatenate both numbers and stringsprint("This will concatenate numbers ".. 4053 .." strings " .. 32)--joining a value from a table to anothertableVal = {"this", "is", "table", 3};print(tableVal[2] .. "join them")
Lines 3–6: We declare the variables.
Lines 9 and 11: We use the double dots concatenation operator, ..
, to concatenate and print the values of the earlier declared variables.
Line 14: We try a concatenation of both numbers and strings.
Line 17: We defined a table variable.
Line 19: We concatenate a single element from the earlier declared table with another.
The code snippet below will have some concatenation attempts that are illegal and will throw an error:
tableVal = {"this", "is", "table", 3};--this operation will throw an error.print(tableVal .. "join them")
In the code snippet above, the attempt to concatenate a table with a string value throws an error.