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

Way to set a string value into another string value? pt. 2

Look at part 1 first: https://scriptinghelpers.org/questions/113470/way-to-set-a-string-value-to-a-number-value

I've got another problem with my code. I used the tonumber() function and now when I type in a string and click the CalculateButton it gives me this error: attempt to perform arithmetic (add) on nil Anyone know how to fix this so if there's a string and I press calculate, it does nothing and if I type in a number, it will work?

Here's the code:

print("Ready for calculating")
while true do
	wait(0.1)
	
	local player = game.Players.LocalPlayer
	local character = player.Character
	local playergui = game.Players.LocalPlayer.PlayerGui
	local calculatebutton = playergui.ScreenGui.CalculateButton
	local textbox1 = playergui.ScreenGui.TextBox1
	local textbox2 = playergui.ScreenGui.TextBox2
	local answerbox = playergui.ScreenGui.AnswerBox
	
	calculatebutton.Activated:Connect(function(activated)
		if activated then
			answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
		end
	end)
end

2 answers

✓ Accepted answer

Yes the tonumber function just changes to number if there is not letter on it, else it will return nil, try this check:

	    calculatebutton.Activated:Connect(function(activated)
	        if activated then 
                    if type(tonumber(textbox1.Text) ~= "nil" and type(tonumber(textbox2.Text) ~= "nil" then
	            answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
             else
                   answerbox.Text = "The text you entered wasn't a number!"
                end
         end

Hope it helps

1 comment

0

Thanks, it works like a charm!

Thank you yuni_Boy1234 for helping me! I had to change up some stuff but it works perfectly!

print("Ready for calculating")
while true do
	wait(0.1)
	
	local player = game.Players.LocalPlayer
	local character = player.Character
	local playergui = game.Players.LocalPlayer.PlayerGui
	local calculatebutton = playergui.ScreenGui.CalculateButton
	local textbox1 = playergui.ScreenGui.TextBox1
	local textbox2 = playergui.ScreenGui.TextBox2
	local answerbox = playergui.ScreenGui.AnswerBox
	
	calculatebutton.Activated:Connect(function(activated)
		if activated and type(tonumber(textbox1.Text)) ~= "nil" and type(tonumber(textbox2.Text)) ~= "nil" then
				answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
			else
				answerbox.Text = "The text you entered wasn't a number!"
			end
		end)
	end

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