Accessing list of objects by id?
Monkey Forums/Monkey Programming/Accessing list of objects by id?
| ||
Hi, Can you have a list such as in C# like List<MyObject> myLst = new List<MyObject> and then access it with something like object myObj = myLst[5], assuming index 5 has something in it. Can it be done in Monkey? I'm sure it must, but can figure our the right syntax. Thanks |
| ||
Class Moo Global list:List<Moo> Field id:Int Method Make:Void() If Not list Then list = New List<Moo> Local whos:Moo = New Moo whos.id = Int(Rnd(1, 100)) list.AddLast(whos) End Method Method Draw:Void() For Local whos:Moo = EachIn Moo.list If whos.id = 5 prepareForBurgers() EndIf Next End Method End Class Something like this? Just a quick test. |
| ||
There's no direct way to do it for lists (that is why we use arrays and stacks as well as lists, even though lists are better for some things). You have to step through the list. Here is a way to do it:List< MyObject > myList = new List< MyObject > ' Populate list Local ob:MyObject Local count:Int For Local getOb:MyObject = Eachin myList If count = 5 ob = getOb Exit End count += 1 Next ' ob is the sixth object in the list, or Null if the list is shorter than six objects If you found it easy to use a list for some purposes (e.g. creating a list of monsters to populate a dungeon) but would prefer to have an array from now on, you can use the List.ToArray() method. |