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:

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

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:

        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

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!

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

Answer this question