Netlogo Variable Scope with Let

Asked by At

General CS question because I was surprised by behavior of let in Netlogo.

If I declare a variable from within an if statement per below, is it common for the scope of that variable to be limited to that if statement?

I thought scope generally referred to functions rather than constructs like a loop or if statement. How common is that?

if x > y :
     int i = 2
else:
     int i = 3

print(i)

would return: "error: (i) does not exist" 

1 Answers

1
Community On

I´m not sure, if this answers your question, but the Netlogo Programming Guide on local variables, created with let, states:

Local variables

A local variable is defined and used only in the context of a particular procedure or part of a procedure. To create a local variable, use the let command. If you use let at the top of a procedure, the variable will exist throughout the procedure. If you use it inside a set of square brackets, for example inside an “ask”, then it will exist only inside those brackets.

to swap-colors [turtle1 turtle2]
  let temp [color] of turtle1
  ask turtle1 [ set color [color] of turtle2 ]
  ask turtle2 [ set color temp ]
end

The same is true if a local variables is created within an if or ifelse statement. Therefore if you want to use the variable later on, than declare it before and outside the ifelse statement with let. Than assign the value with set within the ifelse statement.