Iterator variable clashes



  • I've noticed a problem if you have a call to a function that contains a loop within another loop and they both use the same variable name for their iterator. It would be good if there was some sort of scope for iterator variables to prevent these clashes, the current solution is to use different names for the iterators but I have a number of library functions that use loops and it's not always easy to keep track of which iterator names are "safe" for each function call.

    Demo:

    //Includes 
    
    //Init
    
    //Functions
    inline function doSomething()
    {
    	for (i = 0; i < 10; i++)
    	{
    		Console.print("Function: " + i);
    	}
    }
    
    //Callbacks
    function onNoteOn()
    {
    	for (i = 0; i < 5; i ++)
    	{
    		doSomething();
    	}
    }
    
    function onNoteOff()
    {
    }
    
    function onController()
    {
    }
    
    function onTimer()
    {	
    }
    
    function onControl(number, value)
    {
    }
    

  • administrators

    Yes this is odd. I need to check the code (the default JUCE javascript implementation is working correctly).

    There is a workaround though:

    inline function doSomething()
    {
    	local i;
    	
    	for (i = 0; i < 10; i++) // i is now `local` and not `var`
    	{
    		Console.print("Function: " + i);
    	}
    }
    
    for (i = 0; i < 5; i ++)
    {
    	Console.print("Outer: " + i);
    	doSomething();
    }
    

    behaves like expected (the only difference is the local i declaration in the inline function. local variables are scoped to their inline function lifespan so this would be the obvious choice here.
    I could tell the parser to accept a local declaration within the for initializer to make it a little bit less awkward.



  • Yep that will work 🙂


Log in to reply
 

4
Online

337
Users

1.0k
Topics

7.0k
Posts

Looks like your connection to Forum was lost, please wait while we try to reconnect.