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:
01 | print ( "Ready for calculating" ) |
02 | while true do |
03 | wait( 0.1 ) |
04 |
05 | local player = game.Players.LocalPlayer |
06 | local character = player.Character |
07 | local playergui = game.Players.LocalPlayer.PlayerGui |
08 | local calculatebutton = playergui.ScreenGui.CalculateButton |
09 | local textbox 1 = playergui.ScreenGui.TextBox 1 |
10 | local textbox 2 = playergui.ScreenGui.TextBox 2 |
11 | local answerbox = playergui.ScreenGui.AnswerBox |
12 |
13 | calculatebutton.Activated:Connect( function (activated) |
14 | if activated then |
15 | answerbox.Text = tonumber (textbox 1. Text) + tonumber (textbox 2. Text) |
16 | end |
17 | end ) |
18 | end |
Yes the tonumber function just changes to number if there is not letter on it, else it will return nil, try this check:
1 | calculatebutton.Activated:Connect( function (activated) |
2 | if activated then |
3 | if type ( tonumber (textbox 1. Text) ~ = "nil" and type ( tonumber (textbox 2. Text) ~ = "nil" then |
4 | answerbox.Text = tonumber (textbox 1. Text) + tonumber (textbox 2. Text) |
5 | else |
6 | answerbox.Text = "The text you entered wasn't a number!" |
7 | end |
8 | end |
Hope it helps
Thank you yuni_Boy1234 for helping me! I had to change up some stuff but it works perfectly!
01 | print ( "Ready for calculating" ) |
02 | while true do |
03 | wait( 0.1 ) |
04 |
05 | local player = game.Players.LocalPlayer |
06 | local character = player.Character |
07 | local playergui = game.Players.LocalPlayer.PlayerGui |
08 | local calculatebutton = playergui.ScreenGui.CalculateButton |
09 | local textbox 1 = playergui.ScreenGui.TextBox 1 |
10 | local textbox 2 = playergui.ScreenGui.TextBox 2 |
11 | local answerbox = playergui.ScreenGui.AnswerBox |
12 |
13 | calculatebutton.Activated:Connect( function (activated) |
14 | if activated and type ( tonumber (textbox 1. Text)) ~ = "nil" and type ( tonumber (textbox 2. Text)) ~ = "nil" then |
15 | answerbox.Text = tonumber (textbox 1. Text) + tonumber (textbox 2. Text) |
16 | else |
17 | answerbox.Text = "The text you entered wasn't a number!" |
18 | end |
19 | end ) |
20 | end |