Agents (turtles, patches, and the observer) execute commands:
ask turtles [pd fd 5 pu]
A procedure is a user-defined command.
Here is the format of a procedure definition:
to PROC-NAME [PARAMS]
LETS + COMMANDS
end
to draw-square12
pd
fd 12
rt 90
fd 12
rt 90
fd 12
rt 90
fd 12
pu
end
to draw-square6
pd
fd 6
rt 90
fd 6
rt 90
fd 6
rt 90
fd 6
pu
end
to draw-square [side]
pd
fd side
rt 90
fd side
rt 90
fd side
rt 90
fd side
pu
end
Note how draw-square generalizes the other two procedures by using a parameter to determine the length of side.
Here's a screen shot after the command:
ask turtles [draw-square 5]
There are four types of variables in NetLogo: turtle attributes, patch attributes, globals (pond attributes), and locals. We can think of a local variable as being a procedure attribute. It exists only while the procedure executes and is only visible inside the procedure.
Local variables are declared as follows:
let VARAIBLE EXPRESSION
After a local has been declared, its value can be changed using the set command:
SET VARIABLE EXPRESSION
Be careful. Don't get set and let mixed up. Let is used to create and initialize the local, while set is used to change a local (or any other type of variable) after it has been declared.
When a turtle executes the following procedure, it draws a pentagon:
to draw-pentagon [side]
pd
fd side
rt 360 / 5
fd side
rt 360 / 5
fd side
rt 360 / 5
fd side
rt 360 / 5
fd side
end
Instead of four fd commands, this one has five. Instead of turning 90 degrees, this turtle turns 360 / 5 degrees.
I'm too lazy to compute 360 / 5, so I let the turtle do it by typing in 360 / 5. (Note that there must be blank spaces on either side of the / or else the turtle will think 360/5 is some kind of undefined name. Stupid turtle!)
This is inefficient. We can let the turtle compute this angle once and store it in a local variable that can be used through out the procedure (but not outside of the procedure):
to draw-pentagon [side]
let
angle 360 / 5
pd
fd side
rt angle
fd side
rt angle
fd side
rt angle
fd side
rt angle
fd side
rt angle
end
Note: Because NetLogo syntax allows names to contain symbols, we need to distinguish between a symbol that's part of a name and a symbol denoting an arithmetic operation. For this reason, arithmetic operators (+, -, *, /) must have blank spaces on either side.
Here's a snapshot of the pond after each turtle is asked to draw a pentagon with side = 5: