Simplified "for loop" syntax in C #

I want to use C # to create a custom scripting language . It will have simple operators that are actually method calls with arguments such as:

Set("C1", 63);
Wait(1.5);
Incr("C1", 1);

Now I want to provide a loop too , and the usual C # syntax with index is too complicated for such a simple thing. For example, I would have this loop 20 times:

for (20)
{
  Wait(1.5);
  Incr("C1", 1);      
}

Is there a way to achieve such a simple cycle, at least close? (for example, calling a wrapped method inside a for statement or the like)

Thanks Marcel

+3
source share
4 answers

create a function that extends ints:

public static class Extensions {

    public static void Times(this int n, Action action) {
        if (action != null)
            for (int i = 0; i < n; ++i)
                action();
    }

}

name it like this:

20.Times(() => {
    Wait(1.5);
    Incr("C1", 1);
});
+2
source

-.

For(20, () => 
    { 
        Wait(1.5); 
        Incr("C1", 1); 
    } );

private void For (int count, Action action)
{
    while (count-- > 0)
        action();
}
+7
 public static class Loop{
     public static void For(int iterations, Action actionDelegate){       
         for (int i = 1; i <= iterations; i++) actionDelegate();
     }
 }

:

class ForLoopTest 
{
    static void Main() 
    {
       Loop.For(20, () => { Wait(1.5); Incr("C1",1); }); 
    }
}
+3

, script :

Declare("myVar", "integer");
Set("myVar", "5");

For("myVar"){Say("Hello");}

:

public class MyScriptInterpreter
{

  // ...

  protected void forLoop(List<String> Params; List<String> Block)
  {
    int HowManyTimes = Convert.ToInt16(Params[0]);

    for (int k=1; k == HowManyTimes; k++) 
    {
       interpretBlock(Block);
    } 
  }


  protected void interpretBlock(List<String> Block)
  {
    foreach(String eachInstruction in Block)
    {
       interpret(eachInstruction);
    }
  }

  protected void interpret
     (String Instruction, List<String> Params; MyDelegateType MyDelegate)
  {
    if (Instruction == "declare")
    {
      this.declare(Params);
    }
    else if (Instruction == "set")
    {
      this.set(Params);
    }
    else if (Instruction == "for")
    {
      this.forLoop(Params, MyDelegate);
    }
  }
} // class

, for, , , .

, , , , (, ) () , .

, . script, , .

ScriptBegin("FiveTimes");
   Declare("myVar", "integer");
   Set("myVar", "5");

   For("myVar"){Say("Hello");}
ScriptEnd();

PHP - . , script, . , , .

.

0

All Articles