Functions

Topic

Functions

Topic Progress:

Functions are pieces of information or commands which complete a certain task.

They are best used to reduce the amount of repeated code that exists in your programs. They can also help make rather tedious hard-coding efforts into really simple solutions.

In this lesson you will learn how to create functions, and why they are important.

Start by copying the functions project from the following link:

https://x.thunkable.com/projectPage/5f07deba0b45e458aee6e753

If you run the project, you will find that there are 6 labels which all get their values changed to the same text. What text appears depends on what button you press.

If you look inside the blocks, you’ll notice that this simple task has used lots of blocks to do it.

Imagine needing to add even more buttons with new words! Every time you need to add a new label or a new button, you have to go through your code and change several things.

In the case you add a new button, you then need to re-add all the label text changes, which is tedious.

In the case you add a new label, you have to go through every button and add a new label there, which becomes hard to do if your project is rather large.

This can be avoided with functions!

Our function will replace the need to write all these blocks by writing it once and having the function do it for us every time.

Go into the blocks tab, and look for the functions section.

Then drag the function block that does not return. It’s the highlighted one in the below image.

Next you want to give the function a name by replacing the “do something” text.

In this lesson, I will call it “label set”.

Now you want to click on the gear, which is the settings for this function, and add an input variable. This variable also needs an appropriate name.

Appropriate names are useful as it allows people to easily understand the code’s intended behavior.

Now we need to tell our function to do something!

Make the function set all the labels text to the input variable.

In our case, the variable is called Text String. You can find this in the variable tabs after you configure your function properly.

Now that we have our function set up, we can go back to our buttons and clean up the blocks of code there.

Inside the function blocks tab, there is now a block for the label set function. Add this like below!

Now do this for all the other buttons.

Now if you want to add a new label, all you have to do is add one new block into the function, and it will change it for all the buttons correctly.

Also, a new button only requires the function block to work.

Feel free to continue playing around with functions before moving on with the lessons, or see the official thunkable docs at https://docs.thunkable.com/functions

Additionally, you can try to add a new button or a new label to the program yourself.

Move on to the next lesson when you are comfortable with functions.

@

Not recently active