1

I am writing a tic tac toe game for my assignment, and I was stuck with the nested if statement. Attached part of my code below:

if name[1] == "AI" then 
     print("test string")
     playerId = 1
     if level == 1 or level == 2 then
        print("AI lvl 1/2")
        easy()
     elseif level == 3 then
        print("AI lvl 3")
        hard()
     end
elseif name[1] == "player" then
    print("test string2")
    Runtime:addEventListener("touch", fill)
end

while this executed, test string was printed on console, and playerId = 1, but inside 2nd if statement was completely ignored. Not even print on console. Could someone help me solve it please? Or tell me what is wrong with my code. Thanks

5
  • test string2 was printed while name[1] == "player" Commented Nov 5, 2017 at 2:14
  • Check what the value of level is. It sounds like it's something other than 1, 2 or 3. Where are you getting it from? If you post the code where level is defined we might be able to give you some more specific help. Commented Nov 5, 2017 at 3:34
  • in this scene: local level = composer.getVariable("level"), in the difficulty level scene, composer.setVariable( "level", "1" ), level represents difficulty level, only 1,2,3 Commented Nov 5, 2017 at 4:13
  • after adding print("level"..level) below playerId =1 of above codes, it prints level 1/2/3 while I selected related level. Commented Nov 5, 2017 at 4:27
  • Similar to stackoverflow.com/questions/43532017/… Commented Nov 5, 2017 at 10:21

1 Answer 1

3

Add something like print(level, type(level)) to see what level is. Remember, lua can convert strings like '123' to numbers and vice versa when you want to do some arithmetics or string concatenations, but you can't compare strings with numbers like that: 123 == '123' will return false.

So, if level is a string, either replace 1, 2 and 3 in your code with '1', '2' and '3', or convert level to a number: level = tonumber(level)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.