what's wrong with that piece of code? (short)

Started by deltree, Mon 13/10/2003 22:53:46

Previous topic - Next topic

deltree

string name;
InputBox("which room ?",name);
if (name=="1") NewRoom(1);
if (name=="2") NewRoom(2);
if (name=="3") NewRoom(3);
else DisplaySpeech(ROGER,"wrong room");

I put this code on "player enter scene (after fadein)"
When I execute it, even if I enter 1 or 2 or 3, it always displays "wrong room", WHY????

Gilbert

#1
Because you CANNOT use == or = to compare or assign strings. moreover you're missing else's, so the wrong room message may also be displayed when you enter 1 or 2. I can quickly think of two different ways for your code:

1. Convert the string to integer first:
string name;
int nameint;
InputBox("which room ?",name);
nameint=StrToInt(name);
if (nameint==1) NewRoom(1);
else if (nameint==2) NewRoom(2);
else if (nameint==3) NewRoom(3);
else DisplaySpeech(ROGER,"wrong room");

2. Use StrComp():
string name;
InputBox("which room ?",name);
if (StrComp(name,"1")==0) NewRoom(1);
else if (StrComp(name,"2")==0) NewRoom(2);
else if (StrComp(name,"3")==0) NewRoom(3);
else DisplaySpeech(ROGER,"wrong room");


Personally I like method 1 more.

deltree

#2
thanx man!
however, I don't understand the "else":
why is it needed?
let me think....

if I do that then "exit the room"

Whatever goes after will never be executed, will it?

deltree

#3
Quote from: Gilbot V7000a on Tue 14/10/2003 05:19:18
Because you CANNOT use == or = to compare or assign strings. moreover you're missing else's, so the wrong room message may also be displayed when you enter 1 or 2. I can quickly think of two different ways for your code:

1. Convert the string to integer first:
string name;
int nameint;
InputBox("which room ?",name);
nameint=StrToInt(name);
if (nameint==1) NewRoom(1);
else if (nameint==2) NewRoom(2);
else if (nameint==3) NewRoom(3);
else DisplaySpeech(ROGER,"wrong room");

2. Use StrComp():
string name;
InputBox("which room ?",name);
if (StrComp(name,"1")==0) NewRoom(1);
else if (StrComp(name,"2")==0) NewRoom(2);
else if (StrComp(name,"3")==0) NewRoom(3);
else DisplaySpeech(ROGER,"wrong room");


Personally I like method 1 more.

ok thanx, it works perfectly now. (beware,it's not "StrToInt" but "StringToInt")

Pumaman

Quote from: deltree on Tue 14/10/2003 11:53:19
if I do that then "exit the room"

Whatever goes after will never be executed, will it?

Your theory is almost right - except that NewRoom does not take effect immediately; rather, the room transition happens when your script function finishes. So the rest of that script still gets run.

a-v-o

If a character X is in a different room than the current player character and I use SetPlayerCharacter (X); in the script, this doesn't change the room immediately (= same behaviour as NewRoom).

SMF spam blocked by CleanTalk