Home
Project Folders
Teacher Resources
Student Resources
How Do I?
Literacy
MWForum
Site Map
Search
Our Team

MWForum Message [Date Index] [Threads] [Authors] [Attachments] [Subscribe]

[Thread Prev] [Thread Next]

To: "MicroWorlds Forum" <mwforum@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>
Subject: Re: MIA, Ask an Expert: Global Variable Value always the same
From: "Daniel Ajoy" <da.ajoy@xxxxxxxxx>
Date: Mon, 21 Nov 2011 13:56:22 -0500

On Mon, 21 Nov 2011 13:19:57 -0500, <askanexpert@xxxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Hello
The question belongs to the following code:
___________________________________
to begin
lt 40
make "a 130
wendeltreppe :a
end
to quadrat :a
repeat 4 [fd :a rt 90]
end
to wendeltreppe :a
quadrat :a
lt 10
make "a :a - 2
if :a < 70 [stop]
wendeltreppe :a
end
__________________________________
Everything is fine with this code (main procedure is "begin"). But in the definition of global variables it says that they keep their value, even if the procedure is finished. So far so good. In the code, I create the variable with make "a 130. But if you look at the procedure "Wendeltreppe", a gets smaller and smaller every time (with make "a :a - 2). So at the end, the value of a should be something over 70. But if I type in in the command center Show :a after the procedure is finished, it gives the value 130. Why? "A" should be smaller than 130, because it changed during the 3 procedures.
Thank you for your responses!
Fabserl


You have tree variables named a.

One is global,
One is local to quadrat
One is local to wendeltreppe

Procedure declarations like these:

to wendeltreppe :a
to quadrat :a

actually mean:

create a procedure called wendeltreppe, which will use a local variable called a

When, from the "begin" procedure, you say:

to begin
make "a 130
wendeltreppe :a
end

you are actually saying:

the variable "a" will be a global variable, with value 130. Give the value of that variable to the procedure wendeltreppe. Then the procedure takes that value and assigns it to its local variable with the same name.

Therefore, the global variable is never changed.

Instead, try this:

to begin
 lt 40
 make "a 130
 wendeltreppe
end

to quadrat
 repeat 4 [fd :a rt 90]
end

to wendeltreppe
 quadrat
 lt 10
 make "a :a - 2
 if :a < 70 [stop]
 wendeltreppe
end


There, you have only one global variable called "a".

Daniel
OpenWorld Learning



  • Previous by thread: MIA, Ask an Expert: Global Variable Value always the same
  • Next by thread: Re: MIA, Ask an Expert: Global Variable Value always the same

  • To save an attachment to your computer, PC users should right-click (Mac users, click and hold the mouse button) on the link and then choose 'save target as' from the pop-up menu. A window will then pop up in which you can choose a location for the file.


    © copyright 2001 - 2008