Can you help me with my code?


#1

I have a problem with my code. At line 105, it doesn’t find p1 and I don’t know why, so can you help me please?
Here’s the link:
https://editor.p5js.org/Dark_Obsidian/sketches/H1krCM__Q


#2

You’re declaring your p1 variable inside the setup() function, so it’s only in scope inside the setup() function. Try to put together a simpler example:

function setup(){
  let x = 'hello';
}

function draw(){
  console.log(x); // won't work
}

If you want to reference a variable in multiple functions, you need to declare your variable outside of the functions:


let x;

function setup(){
  x = 'hello';
}

function draw(){
  console.log(x);
}

#3
function setup () {
  let p1 = new Player ('z', 's', 50, 1);
  let p2 = new Player ('p', 'm', 425, 2);

Variables declared inside a function cease to exist when that function quits. :skull_and_crossbones:

Unless they become a closure to another inner function. :money_mouth_face:


#4

Thanks, I totally forgot that.


#5

if you declare the variable without the datatype/var/let thing it will be globally scoped
extremely useful for declaring within setup():

function setup(){
  p1 = new Player (loremipsum);
  p2 = new Player (loremipsum);

}

#6

However, if "strict mode"; is active, accessing undeclared variables throws an exception: :scream:

Assignments, which would accidentally create global variables, instead throw an error in strict mode:

'use strict';
                       // Assuming a global variable mistypedVariable exists
mistypeVariable = 17;  // this line throws a ReferenceError due to the 
                       // misspelling of variable