我如何在Smalltalk Pharo中睡几秒钟,并能够打断这一过程



我正在调试一些键盘事件代码,我想用睡眠循环(给我一个创建键盘事件的机会(,但当我这样做时,Pharo不会让我用Command-退出。因此调试是困难的。我不得不等500秒才能修复下面代码中的某些内容。。。

100 timesRepeat: [ 
    Transcript show: 'Type an a... '.
    (Delay forSeconds: 5) wait.
    (Sensor keyPressed: $a) ifTrue: [ Transcript show: 'you pressed a' ].
]

那么我该如何制作命令-。工作,还是有比(Delay forSeconds: 5) wait.更合适的东西?

在Mac OS X上的Squeak中运行良好(使用peekKeyboardEvent,它没有keyPressed:(。所以这不是你的代码的错,中断它应该可以正常工作。

我并不完全相信这在Pharo中有效,但在Squeak中,你可以在一个新的进程中分叉你的代码,这样它就不会阻塞UI:

[
    100 timesRepeat: [ 
        Transcript show: 'Type an a... '.
        (Delay forSeconds: 5) wait.
        (Sensor keyPressed: $a) ifTrue: [ Transcript show: 'you pressed a' ].
    ].
] fork.

我刚开始学习Pharo,似乎你真正遇到的仍然是初学者(包括我自己(的问题。查看您的代码,您似乎希望Transcript每5秒更新一次。以下是如何做到这一点(包括评论以明确某些细微差别(。

| process | "If you're running outside a playground, you should declare the variable, otherwise you should not declare it because it needs to bind to the playground itself"
process := [ 
    100 timesRepeat: [ 
        Transcript show: 'Type an a... '; cr. "I like a newline, hence the cr"
        (Delay forSeconds: 5) wait.
        "In Pharo 10, the following doesn't work, still need to figure out how to do this"
        "(Sensor keyPressed: $a) ifTrue: [ Transcript show: 'you pressed a' ]."
    ]
] fork.
process terminate. "You can run this to terminate the process inside the playground"
process suspend. "Also possible"
process resume. 

最新更新