Login
Community
DARK THEME

Non-positive int treated as undefined

I've been scratching my head over this issue for hours now. The important parts of my code look like this (I'm using JavaScript):

var num;

myFunc = function(){ if (num == 1){ //Do something } }

init = function(){ num = -1; }

update = function(){ num = -1; //Does stuff, sets num = 1 under certain circumstances myFunc(); }

When I start up the game, I get the following error:

Cannot read properties of undefined (reading '0'), in file "main" at line 55

Through some testing, I've found that this only happens if num <= 0. If I change all of those -1's to 1's, I get no error. I've tried every work-around I can think of, like scrapping num altogether and just passing 1 or -1 as an argument to myFunc (which is probably better practice, anyway), but I get the same behavior. What's going on here? Is this supposed to happen?

Sorry in advance, I couldn't figure out how to get the code to format right.

I can't help you with JS, but more details about how to format forum messages are here:

https://microstudio.dev/community/tips/use-markdown-in-forum-posts-and-replies/26/

So source code you just surround with tripple paragraphs :)

@NathanH my guess is that you must have multiple code files. When you define your variable with var num ;, your variable will be local to your current code file but won't be accessible from the context of other files.

If you need to access num from multiple files, make it a global variable. You just have to remove var = num; and keep initializing your variable in init like you did:

init = function(){ num = -1; } 

I hope this helps!

@TinkerSmith and @gilles, thanks guys! I appreciate the help.

I don't have multiple files, but it turns out I wasn't listing all of the important code after all. When the variable was set to a negative value, it was causing me to try to access an index in an array that was out of bounds, but it was just giving me the generic error for trying to read properties of undefined instead of giving me an actual index out of bounds exception.

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community