NetLogo - setting variable in calling breed in nested ask of same type of breed

52 Views Asked by At

I'm trying to set "parent" variable in a nested ask but without luck.

In code below I use an "outer" ask instruction "ask turtle 0" and below this a nested "ask other turtles". In the nested ask I'm trying to set a variable of the calling turtle.

turtles-own [
  a
  b
]

to setup
  clear-all
  set-default-shape turtles "circle"
  setup-turtles
  reset-ticks
end

to go
  ask turtle 0 
  [
    set a 2
    set b 3 
    show (word "(a, b) = (" a ", " b ")")
    ask other turtles 
    [
      show (word "(a, b) = (" a ", " b ")")
      set a a + 1
      set b b + 1
      show (word "(a, b) = (" a ", " b ")")
      ; Below isn't allowed. Message is: 
      ; This isn't something you can use "set" on. 
      ; set ([b] of myself) 14
    ]
  ]
  tick
end

The "set ([b] of myself) 14" instruction doesn't work and the message is "This isn't something you can use "set" on.".

Edit: added clarification below: Let me elaborate a little.

Running the go procedure once gives:

(turtle 0): "(a, b) = (2, 3)"
(turtle 1): "(a, b) = (0, 0)"
(turtle 1): "(a, b) = (1, 1)"
(turtle 2): "(a, b) = (0, 0)"
(turtle 2): "(a, b) = (1, 1)"
(turtle 3): "(a, b) = (0, 0)"
(turtle 3): "(a, b) = (1, 1)"

However, what I would like to happen is that turtle 1, 2 and 3 can write "back" to turtle 0, so that when "go" procedure is run next time I'll set something like:

(turtle 0): "(a, b) = (2, 14)"
(turtle 3): "(a, b) = (1, 1)"
(turtle 3): "(a, b) = (2, 2)"
(turtle 1): "(a, b) = (1, 1)"
(turtle 1): "(a, b) = (2, 2)"
(turtle 2): "(a, b) = (1, 1)"
(turtle 2): "(a, b) = (2, 2)"
2

There are 2 best solutions below

0
On BEST ANSWER

A turtle can access the variables of another turtle but it can't change the variables of another turtle. So you will have to go back to the original turtle and ask them to change their own variable using ask myself [...]

ask turtle 0 
  [
    ask other turtles 
    [
      ask myself [set b 14]
    ]
]
2
On

This error is appearing because you are not using the proper way of setting variables in NetLogo. Instead, you should use:

ask other turtles 
    [
      show (word "(a, b) = (" a ", " b ")")
      set a a + 1
      set b b + 1
      show (word "(a, b) = (" a ", " b ")") 
      set b 14
    ]

That is because what you wanted to be set ([b] of myself) 14 is inside ask other turtles []. When code inside that is run, it is applied to each individual turtle in the specified set (in your case, all turtles except turtle 0) until all of them has followed the instructions you gave them. So writing that of myself is kind of redundant in there.