Search code examples
mit-scratch

Simulating a custom reporter block in Scratch?


In Scratch 2.0, support for custom stack blocks (procedures) was added. But is there any way to use this to "abstract away" logic that returns a value?

For example, i have here a script to naively calculate exponents: (view graphic representation)

set [base v] to [2]
set [index v] to [3]
... // above is for initializing
set [result v] to (base)
repeat until <(index) = [1]>
  set [result v] to ((result) * (base))
  change [index v] by (-1)

How could i export this logic to a "custom reporter" to reuse?


Solution

  • The easiest way to do this is by creating a custom command block, and storing the return value in a variable. This has some drawbacks, such as not allowing recursive calls, but works in most cases. I also recommend setting the block to run without screen refresh.

    Simply define it like this, with the return value available as result:

    define (base) ^ (exp)
    set [index v] to (exp) // need a variable, as arguments are immutable
    set [result v] to (base)
    repeat until <(index) = [1]>
      set [result v] to ((result) * (base))
      change [index v] by (-1)
    

    It can then be called like:

    when gf clicked
    (4) ^ (3) // the stack block
    say (join [4 ^ 3 = ] (result)) // result is set by the [()^()] block
    

    See this in rendered ScratchBlocks.