Looping String.Split() Not Working

Hello! I am attempting to make a function that loops through string.split(), but it does not look like the loop is picking up the result.
:rocket: What do I want to achieve?
I am attempting to make a function that converts a string with commas into an array. Here is an example:
"Test 1,Test 2,Test 3" :arrow_right: {"Test 1", "Test 2", "Test 3"}
:x: What is the issue?
The output of the function is always: image
:white_check_mark: What solutions have I tried so far?
I have tried to look up solutions on the DevForum, but there are no answers that help!

:page_with_curl: The Code
image Script

function CommaStringToArray(InputString)
	print(InputString) -- This will print the InputString parameter correctly!
	local ArrayResult = {}
	for CurrentIndex, CurrentString in pairs(string.split(InputString, ",")) do
		print(CurrentString[CurrentIndex]) --> nil
		table.insert(ArrayResult, CurrentString[CurrentIndex])
	end
	return ArrayResult
end
print(CommaStringToArray("Test1,Test2,Test3")) --> nil
print(CommaStringToArray("Test")) --> nil

What is the issue here? Am I missing something?

Thanks,
image TriumphantCreatorX

I’m confused as to why you wouldn’t run it like this?

function CommaStringToArray(InputString)
	return string.split(InputString, ",")
end
print(CommaStringToArray("Test1,Test2,Test3")) --> nil
print(CommaStringToArray("Test")) --> nilprint("Hello world!")

String.split returns an array anyway?

2 Likes

Hello, @AstraI_YT!
This was because I was most likely going to add more to the function. I am curious as to why looping string.split() does not function and returns nil values. I will mark your reply as the solution because it works as intended, thank you! It looks like looping string.split() is not possible.

You were using for i,v in pairs not ipairs, the index is nil if you use pairs as they are an array, not a dictionary.

IF you used for i,v in ipairs it would work.

Best practice to always use ipairs if it isn’t a dictionary.

2 Likes

The index isn’t ‘nil’ if you use the ‘pairs’ iterator factory function but the order in which the iterable (table) is traversed over in is undefined.