Question regarding strings and loops

How can I loop through a string and print out all the characters in order?

Ask all necessary questions you need.

1 Like
local word = "Cupcakes and Grenades"

for i = 1,string.len(word) do
	local letter = string.sub(word,i,i)
	print(letter)
end
2 Likes
for Character in string.gmatch("string", ".") do
    print(Character)
end

we can do this using gmatch
“.” is any character so it goes through each character at once

2 Likes

I didn’t know it was that easy. Thank you for this.

1 Like

What about if I wanted to get the number position of a certain letter using that loop? for example:

for Character in string.gmatch("string", ".") do
    print(Character)
end
--//Prints: 
s
t
r 
i
n
g

lets say I wanted to get the index number of the letter “r”. How would I do that?

well in this case I would use @Xitral’s idea

function LoopThroughCharacters(String, Function)
    for Position = 1, string.len(String) do
        Function(Position, string.sub(String, Position, Position))
    end
end

LoopThroughCharacters("string", function(Position, Character)
    print(Position, Character)
end)

if you made it a function, you won’t have to create a new line for a variable