Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Attempt to compare number with nil?

box = script.Parent

while wait() do
	number = tonumber(box.Text)
	if number > 90 then
		box.Text = 90
	elseif number < 0 then
		box.Text = 0
	end
end

I get the error attempt to compare number with nil

I could be doing something dumb, I never used tonumber, but it's neccesary here.

2 answers

✓ Accepted answer

tonumber() returns nil if the argument can't be converted into a number, for example, if it's empty.

Try this:

box = script.Parent

while wait() do
    number = tonumber(box.Text)
    if number and number > 90 then
        box.Text = 90
    elseif number and number < 0 then
        box.Text = 0
    end
end

1 comment

0

Ouch to think this was all a cuz of a typo. Thanks.

If you use tonumber on a string that can't be converted to a number, it'll return nil.

print(tonumber("Hello, world!")) -- nil

Therefore, you can simply check if it returns nil.

-- I converted all your variables to local variables. Always use local variables.

local box = script.Parent

while wait() do
	local number = tonumber(box.Text)
	if number then -- this checks if number isn't nil
		if number > 90 then
			box.Text = "90" -- set text to a string
		elseif number < 0 then
			box.Text = "0" -- set text to a string
		end
	end
end

There are ways you can make this code better by using events, particularly the Changed event, or GetPropertyChangedSignal thingy, but for now it's probably not that big of a deal.

This discussion is preserved as it was. New answers, comments, and votes are closed.