Is it possible to do an if/else within an if/else?

Started by Tyshalle, Tue 05/11/2013 00:08:45

Previous topic - Next topic

Tyshalle

I'm curious if it's possible to run if/else statements within if/else statements. Like for instance, let's say you use a specific inventory item on an object or hotspot, but you want the object/hotspot's reaction to vary depending on other factors too, such as whether or not you have another inventory item as well. Is this possible?

For example, if the player is trying to get past a guard dog, he might use a doggy treat from his inventory on the dog. But you might want to say that if the player has bacon in his inventory too, then the dog won't be distracted.

So could you write something like this?

Code: ags

function cGuardDog_UseInv()
{
  if (cEgo.ActiveInventory == iDogTreat) {
    cEgo.LockView(5);
    cEgo.Animate(3, 1, 0, eBlock, eBackwards);
    cEgo.UnlockView();
    if (cEgo.HasInventory(iBacon) {
      cGuardDog.Say("Woof! Woof!");
      cEgo.Say("He seems to be attracted to my bacon more than dog treats.");
    }
    else {
      cGuardDog.Walk(352, 451, eBlock, eWalkableAreas);
      cEgo.Say("Nice, it worked.");
    }
  }
}
[/code}

When I try something like this, I get an error message saying "end of input reached in middle of expression" aimed at the second "if" statement.

If this isn't possible, is there some other kind of a workaround?

DoorKnobHandle

Of course that's possible. :)

But I wonder, why not just try it out? Since you've already written the code, surely that's faster than making a thread here?

Khris

You forgot a closing parenthesis:

    if (cEgo.HasInventory(iBacon))

Tyshalle

Sorry, for some reason the last thing I said showed up in the code block, but I did try it. But I got back an error message that said "end of input reached in middle of expression".

Khris pointed out the solution though. Worked like a charm, which is excellent. Silly oversight on my part, I just forgot the second closing parenthesis and assumed the error message had something to do with the if within an if statement since this was the first time I tried it.

Thanks a ton!

monkey0506

Just for your future reference, the "end of input" error message from AGS generally indicates you forgot a closing parenthesis or brace somewhere. Oh, and the end of your other post showed up inside the code block because you typed a curly brace instead of a square bracket:

You typed:  [/code}

The correct closing tag is:  [/code]

These things are especially important in programming.

SMF spam blocked by CleanTalk