Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to split string into chars and put them into array (list)?

I want to create 1, specific string and then put them into the array like this:

local myString = "example string"

and then get in result:

local myList = {"e","x","a","m", etc. }

2 answers

✓ Accepted answer

you use string.gmatch() and use the "." string pattern, which is every character inside a string. then just literate over it and insert each character into a table.

local myString = "example string"
local myTable = {}

for character in string.gmatch(myString,".") do
	table.insert(myTable, character)
end

then if you want, you can literate over the table and print each character or value.

for _,v in pairs(myTable) do
	print(v) -- just prints the value or the character
end
  • e
  • x
  • a
  • m
  • p
  • l
  • e
  • s
  • t
  • r
  • i
  • n
  • g

2 comments

0

Just in case for anyone who might not know what is gmatch, it returns an iterator function, kinda like how pairs returns next

0

Thanks, very helpful. :D

This is easily done with just string.sub and a basic for loop.

function getChars(InputString)
	local ret = {}
	for local i = string.len(InputString), 1, -1 do -- For every character
		ret[i] = string.sub(InputString,_,_) -- Add this character to the table
	end
	return ret
end

4 comments

0

why are you using _

0

^ You should only use _ if it's a value that won't be used. E.g for _, v in pairs. If you have no need for the index.

0

Thanks for help, I don't need it, as @up already did explain, but thanks for help, meaning is the most important. ;)

0

Changed it to not use _

This discussion is preserved as it was. New answers, comments, and votes are closed.