If the title does not explain clearly enough, my doubt is this: How can (If we can) we convert a string into a table? For example, I have a string value. The string is "MyStringvalue". Keep in mind that it's the STRING, not the NAME OF THE STRING. So now, in my table, I want the first term in the table to be "M". The second is "y". Case sensitive. The third will be "S" and so forth. Is there a way we can do this? And if so, how?
There's a few ways of doing it:
01 | local myString = "Hello World" |
02 | local characters = { } |
03 |
04 | --putting string in table by looping through each position in the string |
05 | --and getting the substring at that position (the character at that position |
06 | for i = 1 , #myString do |
07 | table.insert(characters, myString:sub(i,i)) |
08 | end |
09 |
10 | --print out the characters array to show that we put the string in the table: |
11 | for _, character in pairs (characters) do |
12 | print (character) |
13 | end |
1 | --use string.split("") to split up every character and put it into a table |
2 | local myString = "Hello World" |
3 | local characters = myString:split( "" ) |
4 |
5 | --print out the characters array to show that we put the string in the table: |
6 | for _, character in pairs (characters) do |
7 | print (character) |
8 | end |
Both ways work, but I prefer string.split(myString,"")
(approach two) since it's faster to write out.
Both have same speeds really.