Jump to content




How to loop through all the chars in a string


  • You cannot reply to this topic
3 replies to this topic

#1 houseofkraft

  • Members
  • 170 posts
  • LocationUSA

Posted 10 November 2016 - 01:42 AM

Hi Guys!

I was wondering how to make some kind of while true do loop that cycles through the chars one by one in a string (variable)

Thanks!

- House

#2 Dog

  • Members
  • 1,179 posts
  • LocationEarth orbit

Posted 10 November 2016 - 02:00 AM

You don't need a while/do loop - this should work for you...
local word = "Test" --# test string
for i = 1, #word do --# start a loop that iterates as many times as there are letters in the test string
  print(word:sub(i, i)) --# print a string.sub() of the test string (printing only the letter the loop is currently on)
end


#3 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 10 November 2016 - 06:06 AM

View PostDog, on 10 November 2016 - 02:00 AM, said:

You don't need a while/do loop - this should work for you...
local word = "Test" --# test string
for i = 1, #word do --# start a loop that iterates as many times as there are letters in the test string
  print(word:sub(i, i)) --# print a string.sub() of the test string (printing only the letter the loop is currently on)
end

There's this too
local text = "Hello World"
for char in text:gmatch "." do
 print(char)
end
But it all comes down to personal preference.

Edited by H4X0RZ, 10 November 2016 - 06:07 AM.


#4 Admicos

  • Members
  • 207 posts
  • LocationTurkey

Posted 10 November 2016 - 11:20 AM

View PostH4X0RZ, on 10 November 2016 - 06:06 AM, said:

View PostDog, on 10 November 2016 - 02:00 AM, said:

You don't need a while/do loop - this should work for you...
local word = "Test" --# test string
for i = 1, #word do --# start a loop that iterates as many times as there are letters in the test string
  print(word:sub(i, i)) --# print a string.sub() of the test string (printing only the letter the loop is currently on)
end

There's this too
local text = "Hello World"
for char in text:gmatch "." do
print(char)
end
But it all comes down to personal preference.

And this:

a = "some string"
a:gsub(".", function(char)
    print(char)
end)






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users