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
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
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