How do functions work?

i only really know the bare minimum about functions, calling lines of code without any other special things. i know there are more things i can add like sprites, variables, and booleans, but how?

8 Likes

As far as I’m concerned, you can simply create/initialize variables (any type of them, whether they’re boolean, integer, or decimal) inside a function; they are called local variables. And, as the name implies, they’re local, they can only be accessed through the function.

image

Sure, the program won’t break down if you decide to use the local variable outside of the function, however, in reality, you just made 2 variables of the same name.


Button Local Variables

If you want a function to spawn a sprite, I’d use a local variable (variables that can only be accessed in a specific function), and assign a sprite for the variable, for example: if I wanted to spawn a button at a random location every time I pressed spacebar, I would’ve wrote this function down here.
image

Here’s the code:

Hmm without much context I can’t help you.

You can essentially make a custom block
Example: I’m trying to add custom emotion animations
image


Now the text inputted in the function is sent to the bottom line
this just stores it on the sprite

Finally, the data is read in this if statement and the sprite animates
image
This is useful for repeating the same action - displaying an emoji on a sprite
but also making it able to be used for multiple different emoji types

Example 2: moving a sprite


Can edit the number of times the sprite moves, the amount it moves by, and the pause between each move repeat (can add even more if you want to customise further)
This is useful for making custom movement with only 1 function (less blocks)
also makes it easier to edit the code as changes affect all 4

2 Likes

By add more things, do you mean adding parameters?

1 Like

Look at the code from The Makecode Forums. It’s pretty self explanatory

1 Like

Just…look at this:


This is very simple, but so, so much more can be done.
Here is the project if you want to change it to a different language or mess around with it :slight_smile:

1 Like

MakeCode doesn’t support local variables in blocks, everything is global. :sob::sob::sob:

So if you used a recursive function for example, it would definitely break.

4 Likes

Yeah.