3

在 Scratch 2.0 中,添加了对自定义堆栈块(过程)的支持。但是有没有办法使用它来“抽象”返回值的逻辑?

例如,我在这里有一个脚本来天真地计算指数:(查看图形表示

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)

我如何将此逻辑导出到“自定义报告器”以重用?

4

3 回答 3

1

这是一个示例(渲染):

define split [text] by [splitter]
delete (all v) of [output list v]
set [parse v] to [0]
set [cur string v] to []
repeat until ((parse) > (length of (splitter))
   if <(letter (parse) of (text)) = (splitter)> then
      add (cur string) to [output list v]
      set [cur string v] to []
   else
      set [cur string v] to (join (cur string) (letter (parse) of (text)))
   end
end

when GF clicked
split [Hello, world! Do you like this?] by [ ] // That's a space.

// That should output a list: ["Hello,", "world!", "Do", "you", "like", "this?"]

define the answer to life
set [output var v] to (42)

when GF clicked
the answer to life
say (output var)

它展示了如何同时使用列表输出和变量输出。

于 2015-02-23T23:12:55.567 回答
0

最简单的方法是创建一个自定义命令块,并将返回值存储在一个变量中。这有一些缺点,例如不允许递归调用,但在大多数情况下都有效。我还建议将块设置为在不刷新屏幕的情况下运行。

像这样简单地定义它,返回值可用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)

然后可以这样调用它:

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

在渲染的 ScratchBlocks 中看到这一点。

于 2015-01-14T16:50:57.977 回答
0

还有第二种更复杂的方法可以做到这一点。它允许递归块,您可以多次运行一个块。我称它为堆叠方法,因为我使用列表作为堆栈。例如,请参阅我制作的这个项目

此方法也不会弄乱变量调色板。

define (base) ^ (index) recursive
if <(index) = [1]>
  add (base) to [stack v]
else
  (base) ^ ((index) - (1)) recursive // adds the previous item to the stack
  add ((base) * (item (last v) of [stack v])) to [stack v]
  delete ((length of [stack v]) - (1)) of [stack v] // clean up

然后可以使用与我在另一个答案中解释的基本相同的方法访问它:

when gf clicked
(4) ^ (3) recursive // the stack block
say (join [4 ^ 3 = ] (item (last v) of [stack v])) // get the item from the end of the stack
delete [last v] of [stack v] // optional, if you want to clean up

在渲染的 ScratchBlocks 中看到这一点。

于 2015-01-14T16:52:14.727 回答