Netlogo: issue with patches attributes as input variable to procedure

Viewed 26

thanks to a fellow stack-overflower, i have recently learned how to use 'run-result' to pass patch attributes as input variables to a procedure. However, i am struggling using the same approach when i want to modify the patch attribute. To clarify, in the code below, i am successfully passing the attribute 'attr1' to Export.List.to.file, but when I pass it to Import.List.from.file, i get an 'this isn't something you can use set on' error in the line 'ask datum [set (run-result #attr) file-read]]'

can anyone help?

to setup
  clear-all
  let patch-list sort patches
  ask patches [set attr1 random 10]
  
  Export.List.to.file "attr1" patch-list "attr1.txt"
  Import.List.from.file "attr2" patch-list "attr1.txt"
end

to Export.List.to.file [#attr #patch-list #filename]
  let list1 map [ p -> [run-result #attr] of p ] #patch-list
  carefully [file-delete #filename] []
  file-open #filename
  foreach list1 [?datum -> file-print ?datum]
  file-close  
end

to Import.List.from.file [#attr #patch-list #filename]
  file-open #filename
  foreach #patch-list [datum -> ask datum [set (run-result #attr) file-read]]
  file-close
end

1 Answers

To be perfectly honest, I can't explain exactly why it doesn't work in the second case and does work in the first case. My best guess is that in the first case, the attribute is treated as a reporter, something to be used by other processes. In the second case, the attribute is treated as a property, for which different rules apply.

The workaround I would use is to turn the entire set command into a single string, and then turning it back into a command by using run. To combine the different parts of the command into a single string, you can use word: let commandstring (word "set " #attr-name " random 5"). Notice how I use quotation marks for "set " and " random 5" but I don't use them for #attr-name, since I don't want #attr-name in the final string, but rather the string contained within #attr-name. In my case that would be "attr3".

to go-3
  
  change-attribute "attr3" patches
  
end


to change-attribute [#attr-name patchset]
  
  let commandstring (word "set " #attr-name " random 5")
  
  show commandstring 
  ; this gives "set attr3 random 5"
  
  ask patchset [run commandstring ]
  
end
Related