The problem is that conditional sentences they keep bugging for me i tried elseif and even else if (seperate) but the problem is it always registers the first "if" even if the requirements are not met and its really annoying here is a example of what i mean
local No = math.Random(1,20) if No = 4 or 8 or 12 or 16 then print("Multiple of 4") elseif No = 5 or 10 or 15 or 20 then print("Multiple of 5") else print("Random Number") end
The problem is that it will always print Multiple of 4 even if the requirements arent met and it really annoys me alot i even tried
local No = math.Random(1,20) if No = 4 or 8 or 12 or 16 then print("Multiple of 4") else if No = 5 or 10 or 15 or 20 then print("Multiple of 5") else print("Random Number") end end
But it still does the same result of always printing the if statement even if requirements arent met so can u help me figure out whats the problem?
You’re using the assignment operator in a conditional statement, which essentially confuses the logical operation, it’s understanding "assign he variable No
to 4". There is a large difference between the assignment and comparison operands within coding languages, and this needs to be understood quickly as you can cause a lot of semantic errors, as seen above.
The operator you need to use is ==
. This doesn’t solve your problem however, you cannot recursively call or
in this scenario without properly providing another comparison expression, this is what’s causing the conditional to pass regardless of the malformed statement.
On a positive note, you can concur if a number is a multiple of a factor by using the modulo operator %
, which retrieves the remainder of a division; in the case of x
being a factor of y
would be 0
. This will allow us to run a single condition, without needing to compensate for range.
local Number = Random.new(tick()):NextInteger(1,20) local Factor1 = 4 local Factor2 = 5 if ((Number%Factor1) == 0) then print(Number.." Is a factor of "..Factor1) elseif ((Number%Factor2) == 0) then print(Number.." Is a factor of "..Factor2) else print(Number.." isn’t a factor of "..Factor1.." or "..Factor2) end
if
calls a conditional scope. elseif
provides an alternative condition. else
concludes all conditions aren’t met.
If you’re wondering what Random.new() is, this is a more dirverse form of math.random
. It returns a Random Object that can be initiated with a seed, which allows us to build a more randomized pseudo-random number. It contains many methods allowing us to be versatile on our return calculation as well. TL;DR: More efficient and versatile.
local multiples = {[4] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}, [5] = {5, 10, 15, 20}} local No = math.Random(1,20) for i,v in pairs(multiples) do for a,b in pairs(v) do if No == b then print('Multiple of',i) return end end