Countdown

Discussion in 'CommandHelper' started by SoftMC, Sep 4, 2017.

  1. SoftMC

    SoftMC New Member

    This has always stumped me ever since I started using CH. It's such an easy concept, although I just can't seem to get it.
    PHP:
      @cd = @v3;

        set_interval(1000, closure() {
          @cd = @cd - 1;
          foreach(@pl in all_players(@v2)) {
            tmsg(@pl, colorize('&c'[email protected]cd.' &eseconds until the game starts!'));
          }
        });
    Say @cd is 60.
    In chat, It'll say that there are 59 seconds left, and it will just keep repeating it.
    As always, any help is appreciated!
  2. PseudoKnight

    PseudoKnight Well-Known Member

    I explained this a bit in IRC, but I should do it here too for reference.

    closure() creates a copy/clone of the variable list at the point in which it was defined. So each time the closure is run, it uses that copy. So even if you change a variable later in your script, the closure will have its own copy and use that instead. Arrays are different in that they're copied by reference. You can read/modify the values in an array anywhere you have the reference, this includes closures or scripts you import() the variable. So, to modify yourcountdown, we simply wrap your value in an array:

    PHP:
      @cd = array(@v3);

        set_interval(1000, closure() {
          @cd[0] = @cd[0] - 1;
          foreach(@pl in all_players(@v2)) {
            tmsg(@pl, colorize('&c'[email protected]cd[0].' &eseconds until the game starts!'));
          }
        });
    There's some more information about this in the documentation, like here:

    http://wiki.sk89q.com/wiki/CommandHelper/Staged/Closures#Scope
    Last edited: Sep 5, 2017
  3. SoftMC

    SoftMC New Member

    Thanks so much!