Nety
Nety

Reputation: 129

NetLogo: storing variables in list and iterating through them

I want to loop through a range of variables in NetLogo. Idea is that those values are inserted as variables in UI and those values are iterated through in while or foreach loop. Also how to get to each value - in Python it is easy as you iterate through them but if I use NetLogo then I have to take "item x in list", can I access variables in list same way? In Python it is like below:

variables = [x0, x1, x2, x3, x4]
for x in variables:
    print (x)

Output is x0 to x4 as variables to use in code.

Upvotes: 1

Views: 2231

Answers (2)

Nicolas Payette
Nicolas Payette

Reputation: 14972

Luck's answer is correct. But if you have a ton of similarly named variables, be aware that you can also do something like:

let xs map [ [n] -> runresult word "x" n ] range 5
foreach xs [ [x] ->
  print x
]

Upvotes: 2

Luke C
Luke C

Reputation: 10291

If you are asking how to put variables from the UI into a list, you can use the list primitive to build a list of variables that the user input, for example using an "Input" in the UI. Then, you can use foreach to iterate through the items in that list.

  let x_list (list x0 x1 x2 x3 x4 )

  foreach x_list [ 
    [x] ->
    print(x)
  ]

Upvotes: 1

Related Questions