Lua - Array to String Conversion
Array is an ordered arrangement of objects whereas string is a continous sequence of characters. There is no library method available to convert an array to string but we can use concatenate operator to concatenate entries of an array to get a string from an array.
-- iterate the array for i = 1, #array do -- concatenate the array entries to a string text = text .. array[i] end
Example - Array to String Conversion
In following example, we've used the above approach to convert an array of characters to a string and result is printed.
main.lua
-- create an array of chars
array = {"H", "E", "L","L","O", " ", "W","O","R","L","D","!"}
-- string variable
text = ""
-- iterate the array
for i = 1, #array do
-- concatenate the values to the string
text = text .. array[i]
end
-- print the string
print(text)
Output
When we run the above code, we will get the following output−
HELLO WORLD
Example - Array to String Conversion using function
In following example, we've created a toString() method which can be used to convert any array to a string and result is printed.
main.lua
-- create a function to convert an array to string
table.toString = function(array)
-- string variable
text = ""
-- iterate the array
for i = 1, #array do
-- concatenate the values to the string
text = text .. array[i]
end
-- return string representation
return text
end
-- create an array of numbers
array = {1, 2, 3, 4, 5, 6}
text = table.toString(array)
-- print the string
print(text)
-- create an array of chars
array = {"H", "E", "L","L","O", " ", "W","O","R","L","D","!"}
text = table.toString(array)
-- print the string
print(text)
Output
When we run the above code, we will get the following output−
123456 HELLO WORLD!
Advertisements