创建按钮的函数

Function to creates buttons

我正在尝试创建一个函数来创建按钮(因此请保留 "clean" 代码)。

代码如下:

(
Window.closeAll;

~w = Window.new(
    name: "Xylophone",
    resizable: true,
    border: true,
    server: s,
    scroll: false);

~w.alwaysOnTop = true; 

/**
 * Function that creates a button.
 */
createButtonFunc = {
    |
        l = 20, t = 20, w = 40, h = 190, // button position
        nameNote = "note", // button name
        freqs // frequency to play
    |

    Button(
        parent: ~w, // the parent view
        bounds: Rect(left: l, top: t, width: w, height: h)
    )
    .states_([[nameNote, Color.black, Color.fromHexString("#FF0000")]])
    .action_({Synth("xyl", [\freqs, freqs])});
}
)


(
SynthDef("xyl", {
    |
        out = 0, // the index of the bus to write out to
        freqs = #[410], // array of filter frequencies
        rings = #[0.8] // array of 60 dB decay times in seconds for the filters 
    |

    ...
)

错误是:错误:变量'createButtonFunc'未定义。 为什么?

抱歉,我是初学者。

谢谢!

可能回答这个问题有点晚了,但我希望这可以帮助其他有同样问题的人。

您收到该错误的原因是您在声明之前使用了变量名。

换句话说,如果您尝试评估

variableName

就其本身而言,您总是会遇到错误,因为解释器无法将该名称与其所知的任何其他名称相匹配。要解决此问题,您可以使用全局解释器变量 (a-z)、环境变量(如 ~createButtonFunc),或在代码的前面声明 var createButtonFunc。请注意,最后一个意味着您将无法在解释该块后访问该变量名,这可能是好事,也可能不是好事。如果你想以后能够访问它,我认为写 ~createButtonFunc.

最有意义

顺便说一句,你可以只使用w而不是~w;默认情况下,单字母变量名是全局的,这是惯用的用法。

-布莱恩