This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2013-01-08 08:06:25

mactro
New Scratcher
Registered: 2013-01-02
Posts: 4

Dynamic content of a CustomMenu

I'm making a mod that will connect scratch to Arduino. Currently, I have problems with adding a custom menu, that will allow a user to select a serial port that the Arduino uses from a list of all available ports. That list of course changes dynamically, so I also have an option to refresh it. Below is my attempt to do it:

Code:

 boardMenu: t1 
    | menu ports b t2|
    menu := CustomMenu new.
    b := self workPane board.
    ports:= b availablePorts.

    menu add: 'Refresh ports list' action: b findPort.
    menu addLine.
    ports size = 0 ifTrue: [menu add:'No serial ports found' action: nil].


    ports do: [:t3 | menu add: t3 action: t3].
    t2 := menu startUp.
    t2 ifNil: [^ self].
    b openPort: t2.

Everything works fine, except that findPort method is invoked every time the menu is opened. I know that in other menus, the action is usually a symbol beggining with #, but when I try to do it this way, findPort is never invoked, even when its selected. How can I solve this?

More generally, I need to find a way to find a way to pass an argument to a method selected from a menu, like:

Code:

 menu add:'print something' action:(print:'something')

Offline

 

#2 2013-01-08 11:24:20

LS97
Scratcher
Registered: 2009-06-14
Posts: 1000+

Re: Dynamic content of a CustomMenu

The action parameter is actually just what the "menu startUp:" method will return when an item with the corresponding label is selected: it doesn't actually have to be the name of a method (which is why findPort is always being executed: by setting the action to "b findPort" you're actually setting it to the return value of the findPort method, which obviously has to be executed for it to add it to the menu).

Thanks to this though you can decide to do whatever you want with the result, including passing it to a method that has arguments.

For the code above I suggest you do something like this instead (at the end):

Code:

result := menu startUp.
    result ifNil: [^ self].
    result = #refreshPorts ifTrue: [^ b findPort].
    b openPort: t2.

keeping in mind that the refresh port menu item has to be changed to
menu add: 'Refresh ports list' action: #refreshPorts.

Offline

 

#3 2013-01-12 08:20:51

mactro
New Scratcher
Registered: 2013-01-02
Posts: 4

Re: Dynamic content of a CustomMenu

Thanks a lot, it works like a charm  smile

Offline

 

Board footer