Is this how Globals are supposed to work?... strange behavior

I know the use of globals is frowned upon but I was meessing around with them and have observed some strange behavior. Just wondering if the following scenario makes any sense:

  1. defined a global _G.testVar in main.lua
  2. main.lua loads menu.lua
  3. menu.lua sets testVar=0 and loads game.lua
  4. game.lua increments the value of testVar and the reloads menu.lua
  5. If I print out the value of testVar in menu.lua it is 0.
  6. If I then reload game.lua the value of testVar is once again incremented… to 2. Shouldn’t it just be 1? The global value was reset to 0 by menu.lua. It seems like a new instance of the global variable is created for each .lua file.

I can’t figure out why I am seeing this behavior. Any help would be greatly appreciated! Thanks! [import]uid: 16901 topic_id: 18659 reply_id: 318659[/import]

@txmarsh, you might want to post your relevant code, i.e., all references to _G.testVar in main.lua, menu.lua and game.lua that you have.

Naomi [import]uid: 67217 topic_id: 18659 reply_id: 71689[/import]

Are you sure it’s defined in main.lua? [import]uid: 84637 topic_id: 18659 reply_id: 71709[/import]

When you are calling the testVar variable in the various lua files are you using “_G.testVar” or just “testVar” to access it? [import]uid: 94868 topic_id: 18659 reply_id: 71711[/import]

I was using just testVar… when I try _G.testVar then I always get 0.
I guess this is not normal… I’ll do some more research.
Thanks! [import]uid: 16901 topic_id: 18659 reply_id: 71750[/import]

When you increment it are you also using _G.testVar, or not? If you define something as a global using _G. then you need to use that every time you refer to it, as testVar and _G.testVar are two different things.

Peach :slight_smile: [import]uid: 52491 topic_id: 18659 reply_id: 71787[/import]