How can I loop through a string and print out all the characters in order?
Ask all necessary questions you need.
How can I loop through a string and print out all the characters in order?
Ask all necessary questions you need.
local word = "Cupcakes and Grenades"
for i = 1,string.len(word) do
local letter = string.sub(word,i,i)
print(letter)
end
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
I didn’t know it was that easy. Thank you for this.
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