I want to be able to take a string or text file as an input with one long string present and split each character into string on an array in lua. What is the best way to go about this?
Asked
Active
Viewed 79 times
1 Answers
2
You have several options (although I'm not sure what 2d means in the this context; maybe you can provide an example of both input and expected output?):
- Use string.sub and iterate over string length to extract characters one-by-one and store them in a table
- Use string.gsub with pattern matching one character (something like this should work:
gsub(".", function(s) table.insert(tbl, s) return s)
) - Use string.gmatch for
"."
in a loop inserting characters in a table - Read an external file one char at a time using f:read(1) and storing each result in a table.
- There are some clever answers using string.gmatch in this SO question that avoid loops, but they are likely only applicable to short/specific strings.
All these options are likely to be sub-optimal, but you'll have to provide more information on why exactly you may need to do this, as there may be more appropriate ways to achieve the result depending on the expected outcome. You may need to benchmark these options against your data to see which ones work better.

Paul Kulchenko
- 25,884
- 3
- 38
- 56
-
(2) should probably use `string.gmatch` instead? – Luatic Aug 28 '22 at 09:45
-
yes, it can; will require a loop though. I'll add it as a separate option – Paul Kulchenko Aug 28 '22 at 18:53