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

How do I loop through chars in a string

Started by CCGrimHaxor, 14 February 2015 - 09:04 AM
CCGrimHaxor #1
Posted 14 February 2015 - 10:04 AM
How would I loop through all the chars in the string and put them inside a table?
cdel #2
Posted 14 February 2015 - 10:15 AM
Haven't tested it, but something like this should do the job.


local mystring = "hello"
local chars = { }
for i = 1, #mystring do
  chars[i] = mystring:sub(1, 1)
end
Edited on 14 February 2015 - 09:16 AM
Dragon53535 #3
Posted 14 February 2015 - 10:25 AM
Haven't tested it, but something like this should do the job.


local mystring = "hello"
local chars = { }
for i = 1, #mystring do
  chars[i] = mystring:sub(1, 1)
end
Your code will not work.


local mystring = "hello"
local chars = { }
for i = 1, #mystring do
  chars[#chars + 1] = mystring:sub(i, i) --#1's here should of been i.
end
Edited on 14 February 2015 - 09:26 AM
cdel #4
Posted 14 February 2015 - 10:41 AM
Note to self: dont rush replys :P/>
Bomb Bloke #5
Posted 14 February 2015 - 10:55 AM
Mind you, chars was perfectly fine. Certainly better than pulling the length and adding one over and over.

Double-mind you, you may as well just leave the characters in the string and sub 'em out as needed. Is there any particular need to mirror them into a table?
CCGrimHaxor #6
Posted 14 February 2015 - 11:19 AM
Mind you, chars was perfectly fine. Certainly better than pulling the length and adding one over and over.

Double-mind you, you may as well just leave the characters in the string and sub 'em out as needed. Is there any particular need to mirror them into a table?

Yea because once in the table we can minipulate the chars easier