
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Individual Characters in a Lua String
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 −
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 −
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