Like most programming languages, NetLogo executable phrases can be divided into commands, expressions, and definitions.
Executing a definition creates and names a value such as a variable, reporter, or procedure.
The following example contains four definitions:
patches-own [penergy]
globals [max-penergy]
to update-patch
let new-penergy penergy + 10
set penergy max [new-penergy
max-penergy]
end
Executing a command usually updates a variable (global, local, attribute, or system).
Here are some examples:
set halt? false
fd 5
pu
print "Hello, World!"
The first example is pretty obvious, the halt? variable is being updated to hold the constant value false.
The second and third examples are trickier. In both of these cases attributes of the active turtle are being updated.
The last example is even trickier. In this case we can say that characters are being inserted into the system's standard output stream.
By contrast, executing an expression usually computes a value. The value is lost unless an enclosing command prints it or saves it to a variable.
Here are some examples of expressions:
3.14
e
2 + 3 * 4 – 5 / 6
x <= 10 and x != 5
remainder age 10
1 + random 6
cos(pi / 4)
not felon? and (gpa >= 2.0 or donation > 10000)
Note: What is the value of the third expression? What are NetLogos precedence and associativity rules?
If a procedure is a usr-defined command, then a reporter is a user-defined expression.
Here is the format of a reporter declaration:
to-report REPORTER-NAME [PARAMS]
LETS + COMMANDS
report EXPRESSION
end
Note: There is no rule that says reporters can't contain commands that update variables, although updating a non-local variable from inside a reporter is considered muddy.
Note: The term "reporter" is unique to NetLogo. In most programming languages reporters are called functions and "reporting a value" is "returning a value".
to-report area [radius]
report radius ^ 2 * pi
end
to-report mean-penergy
report mean [penergy] of patches
end
to-report distance-to target-patch
let diff1 pxcor - [pxcor] of
target-patch
let diff2 pycor – [pycor] of
target-patch
let square1 diff1 * diff1
let square2 diff2 * diff2
let sum square1 + square2
report sqrt sum
end
Note: reporters can be turtle-only, patch-only (distance-to), observer-only, or global—meaning any agent including the observer can execute them, this is the case for area and mean-penergy.
Keep in mind, we can't ask agents to execute reporters directly, only commands:
ask turtle 0 [area 10] ; error: command expected
ask turtle 0 [print area 10] ; prints 314.1592653589793