Microsoft MakeCode

Create new blocks comparable to for-loops+functions?


Is there any way to make blocks that are somewhat like for-loops combined with functions: they can be placed in-line with other blocks (like for-loops) and can have parameter values that can be used (like functions). I’d something somewhat like Python’s with statement, that allow variables to be used in a certain context. After looking at I haven’t seen a way to create for-loop-like blocks.

Some background: I want an easy way to allow someone to access all the fields of an object. Currently I’m working on an object based approach that requires “getting” an instance and then passing it to different getter-style methods to extract instance variables. I’d really like a single clamp-style block that gets the object and provides access to a consistent set of all instance variables. (I’m also open to suggestions for other approaches)


Like this?

Screen Shot 2020-06-05 at 8.44.59 AM

Here’s the definition:

//% block="$instance with $num $bool"
//% instance.shadow=variables_get
//% instance.defl=sprite
//% draggableParameters=variable
//% handlerStatement=1
export function exampleHandler(instance: Sprite, handler: (num: number, bool: boolean) => void) {

1 Like

I think that’s exactly what I was looking for (but I’ll have to review/test a little more). Thanks!!!

Quick follow-up: I didn’t see any documentation on this. Is there any? (Or any quick tips…In the absence of info I’ll try to look through the source code)

I’m afraid the only docs are the ones here and they are a little spotty. All the options are defined in the code here but it’s not always obvious what they actually do. Sorry, this is definitely a part of our documentation that needs improvement!

If you ever get stuck, probably best to just ask on the forum like you did :slight_smile:

Since you opened the door to questions… :slightly_smiling_face:

I’m assuming that in this case the Sprite object could be provided (the $instance field), but that .defl=... would use a default sprite variable…Is that correct?

And what’s the instance.shadow about? Getters?

The instance.shadow is the block ID of the default block that gets put in that input. In this case, we want a variable block (with a variable dropdown), which happens to have the ID variables_get.

instance.defl defines the default value for that block. If this was a number, I could put a number in there and that’s what would show up in the toolbox. For variables, it sets the name of the variable to “sprite” in this case. The default-default for variables is the name “item”

1 Like