Need help on a LUA math error

Hey! I’m currently making a hardcap system for a game of mine and need assistance.
What’s happening is that the math is only rendering increments of a specific number as higher than the number, even though originally all of the numbers are suppose to be higher.

This is the module script:

local ButtonHardcaps = {
	["LevelButton"] = {
		["100"] = 20,
		--["5"] = 25,
	}
}

function ButtonHardcaps.GetHardcap(Button)
	local ButtonFromList = ButtonHardcaps[Button.Name]
	
	for i,v in ButtonFromList do
		local Number = (Button:FindFirstChild("Main"):FindFirstChild("Bottom"):FindFirstChild("Number").Text)
		
		if i >= Number then
			return i.." being >= "..Number.." is: "..tostring((i >= Number))
		else
			return i.." being >= "..Number.." is: "..tostring((i >= Number))
		end
	end
end

return ButtonHardcaps

It returns this:
image

I don’t really know what’s happening, any help / assistance would be great!

There doesn’t seem to be anything wrong with your script. Maybe try changing Number to tonumber(Number)?

Also

Since both returns are identical, I don’t think you need the IF statement. just return return i.." being >= "..Number.." is: "..tostring((i >= Number)) will do

1 Like

The issue is Number “100” is actually a string. So when your comparing it “cats” >= 12 doesn’t make sense ( or in this case “100” >= 12). However a string in comparisons is considered a truthy value so I’d imagine it’s effectively turning it to 1 (identical to true*). (1 >= 12).

To fix it. Do as Golden suggested

if tonumber(i) <= tonumber(Number) then
2 Likes

Try doing tonumber(i) instead. Converting Number into a string is probably causing the issue.

2 Likes

Oh yeah. It would need to be done on both since they both appear to be strings.

2 Likes

Yeah. And you probably wouldn’t get far trying to compare strings with math lol. That’s like comparing an English class with an Algebra class


But, it works just fine converting i into a number.
image

2 Likes

The main reason why it generally returns false is you forgot the alphabetical order while working with strings and relational operators.

The variables i and Number are both assigned a string, and are compared while their datatype is string. If you use a relational operator on strings, Lua will check the alphabetical order (not the numbers).

Hence, that’s why "100" >= "2" returns false (since the number two comes after one)

To prevent this happening, you gotta convert the variables to numbers using tonumber()

local indexToNum, numberToNum = tonumber(i), tonumber(Number)

return 'Relational operator ">=" used in: index >= text' .. indexToNum >= numberToNum

Reference

4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.