Computer Science Canada Procedure problems |
Author: | StarFeind [ Wed Jun 15, 2011 9:12 am ] | ||
Post subject: | Procedure problems | ||
I am creating a text game and want to mkae it so that depending on the outcome of this procedure either the part of the story with a monster will be put or the part without the monster will be put, but I cant seem to get it to work. Any ideas?
|
Author: | DemonWasp [ Wed Jun 15, 2011 10:20 am ] | ||||||||||
Post subject: | RE:Procedure problems | ||||||||||
The reason it's not working is because the monster variable is local to the Monsters procedure and cannot be accessed outside of it. As soon as the procedure ends, that variable vanishes. What you really want is a function. I function is exactly like a procedure, except that it returns a value; in this case, probably a boolean value (true or false). The function declaration looks like this:
As soon as you use result, you will exit the function. Then, you can take the value returned like this:
You could also just use the result directly, without storing it locally:
But if you use that, be careful, because each time you reference Monsters, it will run the procedure again (possibly with different results). This can lead to confusing bugs:
You would think that this would only ever say "foo" or "baz", but it turns out it says "bar" pretty frequently: whenever the first call to Monsters returns false, but the second returns true. You can fix this bug by doing the following:
This code will never output "bar". |
Author: | StarFeind [ Fri Jun 17, 2011 8:54 am ] |
Post subject: | Re: Procedure problems |
Ok I got it working but its still got a bug I need ot fix and was wondering if anyone could help me with it. It only words if a monster is generated, if not it quits the program function Monsters : boolean randint (ran, 1, 100) %result true if ran > 60 then result false elsif ran < 60 then end if end Monsters put Monsters if Monsters then % If ran number is over 60 it will not generate a monster put " You live" else % If ran number is less then 60 it will generate a monster put "Your dead end if |
Author: | DemonWasp [ Fri Jun 17, 2011 11:09 am ] |
Post subject: | RE:Procedure problems |
Look at the code inside your function. If ran > 60, then you return false. If ran is less than 60, you...never return anything. Every function must explicitly return a value, so add a "result true" line in there somewhere (up to you where). |