String.split help

I’m trying to split a string at the character “*”. Whenever it’s supposed to split, it creates another string value and sets the value to the split text. Not even sure where to begin.

Edit: Found a way to get it working.

I see you’ve already found your solution, but I’m pasting probably the most efficient way to do this here anyway. Hopefully this gives you at least some small advice.

local splitChar = "*";
local original = "Life*is*like*a*box*of*chocolate!";

local words = string.split(original, splitChar); -- Split whenever * is found.

local function createStringValues(words)
	local strValue = Instance.new("StringValue");
	local _clone;
	for _, word in ipairs(words) do
		_clone = strValue:Clone();
		_clone.Value = word;
		_clone.Parent = workspace; -- location
	end
	strValue:Destroy(); strValue = nil;
end

createStringValues(words);

Instead of ipairs, you could also use for i = 1, #words do, but execution time is almost exactly the same.

When creating new instances, I would create only one instance and clone it, but however you decide, don’t use second argument with Instance.new, unless you are not applying any other changes to properties.

-- Bad
local sample = Instance.new("IntValue", workspace);
-- further property changes here

-- Good
local sample = Instance.new("IntValue");
-- further property changes here
sample.Parent = workspace;

If you are insterested in micro-optimization, which is not at all necessary, using string.split compared to writing a much longer loop is about equally fast as well.

1 Like