Comparing boolean to number error

Hi, i try to make a crate shop where when you click the crate you open it if you have enough money but i see that i get a error regarding comparing boolean to number.

game.ReplicatedStorage.Events.BoughtCrate.OnClientEvent:Connect(function(cratename, category)
	local crate = game.ReplicatedStorage.Items[category].Crates[cratename]
	openingHud.Frame.Crate.Image = crate.Picture.Image
	
	itemsInCrate = crate[category]:GetChildren()
	table.sort(itemsInCrate,
		function(a,b)
			return a.Chance.Value > b.Chance.Value
		end
	)
	
	local randomnumber = math.random(0, 100)
	
	local itemsPreselected = {}
	
	for i, v in ipairs(itemsInCrate) do
		if 100.0 <= randomnumber <= v.Chance.Value and i == 1 then -- Right here
			table.insert(itemsPreselected, v)	
		elseif v.Chance.Value <= randomnumber <= 0 and i+1 == itemsInCrate then
			table.insert(itemsPreselected, v)
		elseif v.Chance.Value <= randomnumber <= itemsInCrate[i+1] then
			table.insert(itemsPreselected, v)
		end
	end
	
	local itemSelected = itemsPreselected[math.round(math.random(1, #itemsPreselected))]
	
	openingHud.Frame.Preview:ClearAllChildren()
	
	local part = itemSelected.Frame.Preview:Clone()
	part.Parent = openingHud.Frame.Preview
	part.Position = Vector3.new(0,0,0)
	
	local camera = Instance.new("Camera", openingHud.Frame.Preview)
	camera.CFrame = CFrame.new(Vector3.new(0,-8, 1), part.Position)
	
	openingHud.Frame.Preview.CurrentCamera = camera
	
	openTheBox()
end)

Okay, the problem happens in your if statements. You have the right idea, but the wrong implementation.

The correct implementation would be:

for i, v in ipairs(itemsInCrate) do
	if 100.0 <= randomnumber and randomnumber <= v.Chance.Value and i == 1 then -- Right here
		table.insert(itemsPreselected, v)	
	elseif v.Chance.Value <= randomnumber and randomnumber <= 0 and i+1 == itemsInCrate then
		table.insert(itemsPreselected, v)
	elseif v.Chance.Value <= randomnumber and randomnumber <= itemsInCrate[i+1] then
		table.insert(itemsPreselected, v)
	end
end

I’ll try it, thanks!
Back then when i was coding in pawn for counter strike i’d do things like these and thought here would work the same.

1 Like

And just to explain it.

This makes perfect sense to a human

100.0 <= randomnumber <= v.Chance.Value

But when a computer reads it, it’s evaluating it in pieces.

So it will do this first

100.0 <= randomnumber -- for the example this evaluates to false

Which will evaluate to true or false. So then it will check the next part which is now

false <= v.Chance.Value

And that is why that errors.

Thank you very much!
This really helps me in understanding Lua more :smiley:

1 Like