Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago

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:

01print("Ready for calculating")
02while 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 textbox1 = playergui.ScreenGui.TextBox1
10    local textbox2 = playergui.ScreenGui.TextBox2
11    local answerbox = playergui.ScreenGui.AnswerBox
12 
13    calculatebutton.Activated:Connect(function(activated)
14        if activated then
15            answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
16        end
17    end)
18end

2 answers

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

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

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

Hope it helps

0
Thanks, it works like a charm! Green_Lime2 80 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

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

01print("Ready for calculating")
02while 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 textbox1 = playergui.ScreenGui.TextBox1
10    local textbox2 = playergui.ScreenGui.TextBox2
11    local answerbox = playergui.ScreenGui.AnswerBox
12 
13    calculatebutton.Activated:Connect(function(activated)
14        if activated and type(tonumber(textbox1.Text)) ~= "nil" and type(tonumber(textbox2.Text)) ~= "nil" then
15                answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)
16            else
17                answerbox.Text = "The text you entered wasn't a number!"
18            end
19        end)
20    end

Answer this question