ScriptCraft

ScriptCraft

14.6k Downloads

Make times() usable inside a Drone method

carlrobert opened this issue ยท 2 comments

commented

Figure out how to make times() work as you'd expect inside a Drone method.

Current limitation: Don't use .times() inside a Drone method implementation - only use it at the in-game prompt as a short-hand workaround for loops.

commented

I guess the problem is that the surrounding, calling, function becomes part of the history and gets repeated as well.

One way to address this could be to let the drone have a stack of histories rather just than a single history.

Prior to invoking the function one could push a new (empty) history onto the stack, and pop it afterwards.
Then every level of invocation will have its own history and whatever gets repeated in that function call context is limited to that context.

Something like

Drone.extend = function( name, func ) {
  if (arguments.length == 1){
    func = name;
    if ( !func.name ){
      throw 'A Drone extension function must have a name!';
    }
    name = func.name;
  }
  Drone.prototype[ '_' + name ] = func;
  Drone.prototype[ name ] = function( ) {
    if ( this.record ) {
      // NEW: Access top element on stack rather than the
      // history attribute (which now is obsolete)      
      this.history_stack[this.history_stack.length-1].push( [ name, arguments ] ); 
    }
    var oldVal = this.record;
    this.record = false;

    this.history_stack.push([]); // NEW: Push empty history into stack

    this[ '_' + name ].apply( this, arguments );    

    this.history_stack.pop() // NEW: Remove top history from stack

    this.record = oldVal;
    return this;
  };

  global[name] = function( ) {
    var result = new Drone( self );
    result[name].apply( result, arguments );
    return result;
  };
};

in src\main\js\modules\drone\index.js

commented

The .times() function was only ever meant to be used at the in-game prompt as an easy way to repeat steps. I'd hope that in a Drone method/extension, programmers would use either while or for loops to achieve the same thing.
As @perfnurt pointed out above, I feel the semantics of the .times() function work best at the command prompt and that getting this to work inside of drone methods probably isn't worth the effort when there are better understood ways of looping.