DeltaWeb
DeltaWeb

Reputation: 381

Why is this booleans always a nil value in all conditions?

So I just starting to learn lua, and I was working on a small script for my game in Corona SDK, but the part of the script is pure lua .

Here's some code :

function checkNumAndExp(number)
local correct;
    if randomText == "bigger than " then
        if number > randomNumber then
            correct = true;
        end
      return correct;
    elseif randomText == "smaller than " then
        if number < randomNumber then
            correct = true;
        end
     return correct;
    elseif randomText == "multiples of " then
        if number%randomNumber == 0 then
            correct = true;
        end
      return correct;
    elseif randomText == "divisible by " then
        if number%randomNumber == 0 then
            correct = true;
            return correct;
        end
    else
      correct = false;
      return correct ;
    end

end

What I'am trying to do is to check if a given number is bigger than or smaller than .... a random number generated at the beginning .

Note : randomText is a random table item string that is equal to one of those values :

  1. Bigger than
  2. Smaller than
  3. Multiples of
  4. divisible by

My current problem is that for all case correct always return a nil value . all other vars are not nil .

Any ideas what would be causing this ?

Upvotes: 1

Views: 54

Answers (1)

Mud
Mud

Reputation: 28991

"Bigger than", "Bigger than ", "bigger than", and "bigger than " are all different strings.


More about your code:

if number > randomNumber then
    correct = true;
end
return correct;

The boolean expression number > randomNumber evaluates to true or false. If it evaluates to true, you then set a variable to true. You can streamline that by using the result of the expression directly:

correct = number > randomNumber
return correct

Given that you're immediately return the result, you don't even need the variable. You can just write:

return number > randomNumber

So your code could have been written:

function checkNumAndExp(number)
    if randomText == "bigger than " then
        return number > randomNumber
    elseif randomText == "smaller than " then
        return number < randomNumber
    elseif randomText == "multiples of " then
        return number%randomNumber == 0
    elseif randomText == "divisible by " then
        return number%randomNumber == 0
    end
    return false
end

Upvotes: 5

Related Questions