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)
@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!