Search code examples
javascriptbbc-microbitmakecode

How do you create global variables in Microsoft MakeCode for micro:bit?


I'm currently trying to create snake inside a micro:bit. But one problem is when I use an if statement to detect if the snake is touching an apple it'll work once but then I call the function which says

function createApple() {
    let apple = game.createSprite(randint(0, 5), randint(0, 5));
}

Creating variables with a let statement makes it a local variable only working with other statements inside of the function, but when I try and make a variable using var it says I must define variables using a let statement. Is there any way to create global variables inside functions and other code blocks that work? (Please answer it in a way that won't be subjective to my situation and will reach across many similar scenarios for people including myself)

(Here's my if statement if it's somehow required by somebody answering)

loops.everyInterval(1, function () {
    if (snakeHead.isTouching(apple)) {
        apple.delete();
        createApple();
    }
});

Solution

  • You can declare the variable outside of the function to make it global. If you start with an empty global variable, you have to add the type of the variable behind :

    let apple : game.LedSprite
    
    function createApple() {
        apple = game.createSprite(randint(0, 5), randint(0, 5));
    }
    

    If you don't know the type of the variable (in this case game.LedSprite) you can find it by hovering the mouse over the function createSprite, see screenshot:

    enter image description here