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

why is this error coming up? im trying to make a limit on how high a number goes.

	if tonumber(script.Parent.Text) < 255 then
	script.Parent.Text = "255"
end

When i do this script it says this error comes up: attempt to compare nil and number  Can you please help me with this peice of code.

If you need any more information please let me know.

7 comments

0

This is for a textbox btw

0

The text is empty.

0

what?

0

The error. Did you read it?

0

You are converting a nil value to a number(which is impossible). You'll need to check if your textbox has a value that is not nil.

0

is this a local or server script?

0

local

2 answers

While using the if statement, the first thing you'd want to check is if the tonumber response is not false. So here's my rewritten code here, I also suggest using FindFirstAncestor rather than script.Parent

local TextBox = script:FindFirstAncestorWhichIsA("TextBox")
if tonumber(TextBox.Text) ~= false and tonumber(TextBox.Text) < 255 then
	TextBox.Text = "255"
end

Well, one of two things is going on here:

  1. #TextBox.Text is 0, meaning there is nothing in the TextBox.

  2. The Text in the TextBox contains something that cannot be converted to a number.

If there is a whitespace character, you can verify this by looping through the string, while using sub() to identify each character:

for i = 1, #script.Parent.Text do
	if script.Parent.Text:sub(i, i):find("%s") then -- Not all whitespace characters are equivalent to " ". You could be weary of unforeseen zero width whitespaces...
		print("Found a whitespace at position " .. tostring(i))
		continue
	end
end	

If it does print, that means #script.Parent.Text is greater than the assumed length if Text was only supposed to contain the number.

If this is not the case, and you have another foreign character, that character should be visible within the TextBox. You can remove the character with ease and move on.

If neither of the above are correct, it means your TextBox's Text is empty. You'll need to fill the text field with a number, and only a number.

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