This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
houseofkraft's profile picture

How to loop through all the chars in a string

Started by houseofkraft, 10 November 2016 - 12:42 AM
houseofkraft #1
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
Dog #2
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
H4X0RZ #3
Posted 10 November 2016 - 06:06 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

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 on 10 November 2016 - 05:07 AM
Admicos #4
Posted 10 November 2016 - 11:20 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

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)