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

Way to set a string value to a number value?

Asked by 4 years ago
Edited 4 years ago

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

2 answers

Log in to vote
0
Answered by
zadobyte 692 Moderation Voter
4 years ago

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)
Ad
Log in to vote
0
Answered by
zane21225 243 Moderation Voter
4 years ago

An easy solution would be to use tonumber.

0
I knew about the tonumber() function and I was using it wrongly in my code. Thanks for the help guys! Green_Lime2 80 — 4y

Answer this question