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

Attempt to compare number with nil?

Asked by 6 years ago
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

Log in to vote
0
Answered by
UgOsMiLy 1074 Moderation Voter
6 years ago

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
0
Ouch to think this was all a cuz of a typo. Thanks. Gashphul 4 — 5y
Ad
Log in to vote
1
Answered by 6 years ago

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.

Answer this question