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

string.sub is responding with invalid argument 2?

It is saying I have an invalid argument. Help please! Code

local spaceLocations = {}
local keyTerms = {}

script.Parent.MouseButton1Click:Connect(function()
	for i=1, string.len(script.Parent.Parent.InputBox.Text) do
		if string.sub(script.Parent.Parent.InputBox.Text, i, i) == " " then
			table.insert(spaceLocations, i)
		end
	end
	for i,v in ipairs(spaceLocations) do
		print(v)
	end
	for i=1,#spaceLocations+2 do
		if i == 1 then
			table.insert(keyTerms, string.sub(script.Parent.Parent.InputBox.Text, 1, spaceLocations[1]))
		elseif i == #spaceLocations+2 then
			table.insert(keyTerms, string.sub(script.Parent.Parent.InputBox.Text, spaceLocations[i], string.len(script.Parent.Parent.InputBox.Text)))
		else
			local term = string.sub(script.Parent.Parent.InputBox.Text, spaceLocations[i], spaceLocations[i]) --Line 56
			table.insert(keyTerms, term)
		end
	end
	for i,v in ipairs(keyTerms) do
		print(v)
	end
end)

Error

21:53:55.851 - Players.benben3963.PlayerGui.ScreenGui.Frame.SearchButton.LocalScript:56: bad argument #2 to 'sub' (number expected, got nil)

5 comments

0

You added +2 numbers to the loop, how come? (Line 13)

0

No reason, I addressed those two added numbers with the if statements. I just want to know why line 19 is not working.

0

Try to print spaceLocations[i] if it is a number

0

error is saying that spaceLocations[i] is nil

0

Mhm, b/c of those 2 added numbers, it's trying to get positions that have no value. :P To stop this, simply do if spaceLocations[i] then

1 answer

✓ Accepted answer

@TheeDeathCaster is right, it is because you add +2 in the loop to #spaceLocations.

You may think that before you arrive to the point where it crashes, you already add more items to your array in your if statements, but that is untrue for two reasons.

First you don't add them to the array spaceLocations, which is what you are looping over. This causes line 19 to crash then i is 1 higher than #spaceLocations.

Then even if you inserted something at the end of the spaceLocations table in each of your two if-statements in that loop, it would not prevent the crash, because


i == #spaceLocations+2 

will not return true. It will each time look at the size of spaceLocations at that point, return false, and subsequently crash on line 19 trying to request spaceLocations[#spaceLocations+1]

(because i is then equal to #spaceLocations+1)

In general it's never a good idea to risk going out of bounds of your loop. Better to call a function in your loop and call that function again for any special cases, so you can still reuse your code.

Good luck!

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