Lua - Loop Through String



A string in Lua is a sequence of characters that we can iterate over in different ways.

In Lua, we have many approaches which we can use to iterate over the characters that made a string, and we can even do anything we want with them, like make use of them in another example, or simply print them.

Let's consider the first and the most basic approach of printing the individual characters of a string.

Example - Looping through characters of a String

Consider the example shown below −

main.lua

-- define a string variable
str = 'tutorialspoint';

-- run a loop from 1 to length of str
for i = 1, #str do
   -- get substring of 1 chracter
   local c = str:sub(i,i)
   -- print char
   print(c)
end

In the above example, we used the famous string.sub() function, that takes two arguments, and these two arguments are the starting index of the substring we want and the ending index of the string we want. If we pass the same index, then we simply need a particular character.

Output

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

t
u
t
o
r
i
a
l
s
p
o
i
n
t

A slightly faster approach would be to make use of the string.gmatch() function.

Example - Printing Characters of String

Consider the example shown below −

main.lua

-- define a string variable
str = 'tutorialspoint';
-- loop over string
for c in str:gmatch '.' do
   print(c)
end

Output

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

t
u
t
o
r
i
a
l
s
p
o
i
n
t
Advertisements