I making code that will add two numbers that are put into a TextBox's Text property and return an answer into another TextBox. The code works perfectly, but if I type in a string and click the CalculateButton, it will give this error in the output: Players.Green_Lime2.PlayerGui.ScreenGui.CalculateButton.LocalScript:15: attempt to perform arithmetic (add) on string
Is there any way to block the strings and only accept numbers? The LocalScript is inside the CalculateButton. 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 = textbox1.Text + textbox2.Text end end) end
You would wanna make use of the tonumber
function. It will convert strings to numbers (assuming those strings are made up of only numbers, or else it will return nil.)
answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
An easy solution would be to use tonumber.