Invalid argument #1 to 'clamp' (number expected, got string)

Well, the following script is basically so that in a text box, you can only put numbers and a certain amount depending on how much value a NumberValue has. I get an error when pressing the Backspace key if there is no number in the textbox, and I don’t know how to fix it

(TextBox)

local selected = script.Parent.Parent.Handler.Selected
local DivideButton = script.Parent.Divide

DivideButton:GetPropertyChangedSignal("Text"):Connect(function()
 if selected.Value ~= nil and selected.Value:FindFirstChild("Stack") then
	DivideButton.Text = DivideButton.Text:gsub('%D+', '')
		DivideButton.Text = math.clamp(DivideButton.Text, 0, selected.Value:FindFirstChild("Stack").Value)
	end
end)

Well, I investigated it and supposedly it is so that you can only put numbers, not letters or signs, only numbers

I believe you are inputting numbers into the math.clamp() as a string. Even if a string is only numbers it is still a string and not a number value.
To convert it do

local number = tonumber(string)
or vise versa
local string = tostring(number)
1 Like

I still don’t know how to use the tonumber and the string, I’ll see what to do

Have you printed DivideButton.Text?

1 Like

a capital %D is everything except a number
a lowercase %d is numbers

1 Like

Yes. I only get error when I press the backspace key if there is no number in the Text of the textbox

In this case, it would return the string “”. Obviously, this isn’t a number, clamp errors. To fix this, I would use tonumber.

local selected = script.Parent.Parent.Handler.Selected
local DivideButton = script.Parent.Divide

DivideButton:GetPropertyChangedSignal("Text"):Connect(function()
	if selected.Value ~= nil and selected.Value:FindFirstChild("Stack") then
		local num = tonumber(DivideButton.Text:gsub('%D+', ''))
		if not num then return end
		DivideButton.Text = math.clamp(num, 0, selected.Value:FindFirstChild("Stack").Value)
	end
end)

Edit: oops wrong function

1 Like

the problem with this is that gsub returns two things(1. the new string, 2. how many times a string was removed)
this means num will always be equal to nil

code that should work
local Selected = script.Parent.Parent.Handler.Selected
local DivideButton = script.Parent.Divide
local Stack = Selected.Value.Stack

DivideButton:GetPropertyChangedSignal("Text"):Connect(function()
    local Number = DivideButton.Text:gsub('%D+', '')

    if Number ~= "" then
        DivideButton.Text = math.clamp(tonumber(Number), 0, Stack.Value)
    end
end)
2 Likes