How to iterate individual characters in a Lua string?

LuaServer Side ProgrammingProgramming

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

After Lua 5.1, 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

Consider the example shown below −

 Live Demo

str = "tutorialspoint"
for i = 1, #str do
   local c = str:sub(i,i)
   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

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

Consider the example shown below −

 Live Demo

str = "tutorialspoint"
   for c in str:gmatch"." do
   print(c)
end

Output

t
u
t
o
r
i
a
l
s
p
o
i
n
t
raja
Updated on 19-Jul-2021 12:35:32

Advertisements