Problem with EachIn?
Monkey Forums/Monkey Programming/Problem with EachIn?
| ||
It may be just my opinion, but I don't think EachIn should be erroring out when trying to access a null (undefined?) object in an array. Example: Class CNode Field x:Int, y:Int Function Create:CNode[](n:Int[]) Local nd:CNode[n.Length+1] ''too big of an array Local i:Int =0 For Local j:Int = 0 To n.Length-2 Step 2 nd[i] = New CNode nd[i].x = n[j+0] nd[i].y = n[j+1] i +=1 Next Return nd End End Function Main() Local node:CNode[] = CNode.Create([5,1,5,6,8,6,4,4]) For Local j:CNode = Eachin node Print "node:" +j.x+" "+j.y Next End Or is this proper behavior? |
| ||
I think it's throwing the error when you try to access the x and y properties of the null object. If you comment out the Print statement, it rolls through the CNode array just fine. |
| ||
Yeah, you just need to test if j is null or not before you print. But if it's actually the For loop that's crashing then that is indeed a bug. |
| ||
You have to always test if returned element is not null, but from my point of view, keyword Eachin is better using with List<T> or Map<K,V> Here is my version of your code: Class CNode Field x:Int, y:Int Field list:List<CNode> Method New() Self.list = New List<CNode> End Method Method Create:CNode(n:Int[]) For Local j:Int = 0 To n.Length-2 Step 2 Local nd:CNode = New CNode() nd.x = n[j+0] nd.y = n[j+1] Self.list.AddLast(nd) Next End End Function Main() Local node:CNode = New CNode() node.Create([5,1,5,6,8,6,4,4]) For Local j:CNode = Eachin node.list Print "node:" +j.x+" "+j.y Next End or Class CNode Field x:Int, y:Int End Function CreateNodeList:List<CNode>(n:Int[]) Local list:List<CNode> = New List<CNode> For Local j:Int = 0 To n.Length-2 Step 2 Local nd:CNode = New CNode() nd.x = n[j+0] nd.y = n[j+1] list.AddLast(nd) Next Return list End Function Main() Local node:List<CNode> = CreateNodeList([5,1,5,6,8,6,4,4]) For Local j:CNode = Eachin node Print "node:" +j.x+" "+j.y Next End |
| ||
Interesting, thanks for the responses. |