How to change agent's variable by passing variable name and value to a function?

僤鯓⒐⒋嵵緔 提交于 2019-12-11 13:33:45

问题


How is it possible to change specific variable of an agent by passing variable name to a function?

for example I have turtles with variable MONEY and the following function:

to setVariable [varname varvalue]
[
   ask one-of turtles [ set varname varvalue ]
]
end

Now I want to run:

observer> ask one-of turtles [setVariable MONEY 100] ;; I need to ask via another turtle since I cannot use MONEY directly in observer context

And it does not set my variable without giving any errors.

Interestingly, you can read a variable in similar manner:

to showVariable [varname ]
    [
       ask one-of turtles [ show varname ]
    ]
end

So the question here is how to "convert" my function input into turtle's variable name it would recognise well for SET purposes.

PS: I don't want to use run function as it would slow down the model. Thanks for any suggestions


回答1:


In a similar situation where there are a number of possible options, I create a task for each and put them in a lookup table (using the table extension) with a string key for each. Then I can lookup the appropriate task for any key. It saves having the nested if/else structures, but I haven't investigated the efficiency of the table lookup.

HTH, Charles




回答2:


You're correct that run with strings would slow down your model, but if you use run with tasks, it won't.

Here's your setVariable procedure rewritten to use tasks:

to setVariable [setter value]
   ask one-of turtles [ (run setter value) ]
end

When you call it, the call will look like:

setVariable task [ set money ? ] 100

But this won't help you if at the call site, there's no way to avoid using strings.

If you must use strings, and it must be fast, then you have no choice but to write out a big ifelse chain that lists all of the variables that you need to support:

to setVariable [varname varvalue]
  ask one-of turtles [
    ifelse varname = "money"
      [ set money varvalue ]
      [ ifelse varname = "food"
        [ set food varvalue ]
        ...
  ]
end

For reading variables, instead of setting, you can safely use runresult with a string containing the variable name without needing to be concerned about performance, since runresult caches the compiled strings, so it will be fast since you'll be passing the same strings over and over. (The setting case is different because the strings you'd be passing to run would be different all the time.)



来源:https://stackoverflow.com/questions/20265782/how-to-change-agents-variable-by-passing-variable-name-and-value-to-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!