0

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();
    }
});
Ametrine
  • 73
  • 6

1 Answers1

2

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

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • When I used `let apple` it says, "Variable 'apple' implicitly has an 'any' type." Is there possibly a fix to this? – Ametrine Nov 10 '21 at 18:12
  • Sorry, yes you have to add the type of the variable if you don't fill it immediately. I edited the answer. – Kokodoko Nov 11 '21 at 09:51