Get the size of a list?

I'm sure this has most likely already been asked, but mobile is being dumb so I can't search, and I'm not going to scour pages of lists of posts for it.
How do I retrieve the size of a list or dictionary so I can randomly choose one in a list/dct that has a changing set of values? And is there a way to get the location of a dctnry? Or do I need a list with the location's names?

(Edit: changed ListCpunt to ListCount in the example code… damn typos)

You can use the function ListCount to get the number of items in a list. Contrary to what the documentation says, it seems to work for dictionaries as well.

In the case of lists, you can use the core functions PickOneString and PickOneObject, which take a single argument (a list) and return a random item from that list. They will generate an error if the returned item isn't the required type.

To get a random item from a dictionary, you would probably want something like:

count  = GetRandomInt (1, ListCount (dict))
foreach (item, dict) {
  count = count - 1
  if (count = 0) {
    key = item
    value = DictionaryItem (dict, item)
msg ("The randomly selected item is key: " + key + ", value: " + value)

(if you were using this in a function, you could use return to end as soon as you find the item you want)

Alternatively, you could keep a separate list of the keys, which is what some of the core functions do, but if the dictionary is modified often this is likely to be less efficient.

Ooh, thanks a ton for this, very helpful! But yes, I am working on a random dungeon generator so the list will be scrambling a ton of times as rooms are generated.

Log in to post a reply.