how to define a global var?

I want to define some global vars and help function, whice is better:

1.global.lua
_G["_W"] = display.contentWidth
_G["_H"] = display.contentHeight
_G[“myHelperFunc”] = function()
return “aa”
end
2.global.lua
_W = display.contentWidth
_H = display.contentHeight

function myHelperFunc()
return “aa”
end

[import]uid: 11702 topic_id: 26572 reply_id: 326572[/import]

I honestly feel it doesn’t matter.
If something needs to be global, add it to _G

Even if you add this to some class in an attempt to be object oriented, you will be defining a singleton, which will ultimately be global anyway.

There are no police looking at your code.

Mind you…

http://imgs.xkcd.com/comics/goto.png [import]uid: 108660 topic_id: 26572 reply_id: 107753[/import]

My opinion is that if you’re going to use globals, use them in such a way that it’s obvious you’ve done so.

[lua]_G._W =
_G["_H"] =[/lua]

are good for this reason if you also make sure to refer to the variables the same way in the future. If later on you look at some code that says

[lua]someObject.x = _W /2[/lua]

and have to wonder, “Wait, was _W a global or did I make a local variable out of it in this module?”, then you did it wrong. [import]uid: 44647 topic_id: 26572 reply_id: 107759[/import]

Sorry for this extreme noob question but I’ve seen “_G” a lot when talking about global variables.

Is _G used by lua? Or is it just as a reminder to yourself that you set that to be a global variable? [import]uid: 123298 topic_id: 26572 reply_id: 108557[/import]

@Axie studio’s: the _G initializes the variable as a global variable, so yes it is used by lua. [import]uid: 84637 topic_id: 26572 reply_id: 108646[/import]

Do you need to add _G? What if you did something like…

[lua]local foo = 3
bar = 6

–Would the variable bar I just declared be the same as…
_G.bar = 6[/lua]

I keep reading that if you don’t add “local” it’s a global variable so I’m getting confused as to why add the _G if it’s already global. [import]uid: 123298 topic_id: 26572 reply_id: 108655[/import]