Why do I have to use _G?

Lets say I have menu.lua containing:

myName = "Tom’;

I then use Director to go to screen 1 and want:

print(myName);

This will show nil. I can however use:

_G.myName = “Tom”;

to set the variable in menu.

But why doesn’t the first example work. I thought everything not local in lua went into _G?

In short, if I set: myName = "Tom’; on a file, why isn’t it accessible forever by all other pages?

Thanks

Tom [import]uid: 55068 topic_id: 13662 reply_id: 313662[/import]

a global variable declared inside a file is global local to that file… so if that variable is not declared in that file you should use _G to get the real global global. :slight_smile:
is it confusing ? [import]uid: 71210 topic_id: 13662 reply_id: 50210[/import]

this sample will give you a better idea

main.lua
[lua]local file2 =require(“file2”)
–global variable a
a = 10

file2:fn1()
–prints 10 – we din’t set _G.a in fn1
print(a)
file2:fn2()

–prints 25-- we set _G.a in fn2
print(a)[/lua]

file2.lua
[lua]module(…, package.seeall)

function fn1()

– prints 10 no other variable a, take the global one
print(a)

–create a new global variable a , won’t affect global a from main
a = 25

–prints 25
print(a)

–prints 10 – we haven’t set value to global a from main
print(_G.a)
end
function fn2()

–sets global variable a
_G.a = 25

–prints 25
print(a)

–prints 25
print(_G.a)
end[/lua] [import]uid: 71210 topic_id: 13662 reply_id: 50218[/import]

Thanks for the help on this. I understand a bit more about how scope between files works now. Cheers!

Tom [import]uid: 55068 topic_id: 13662 reply_id: 50261[/import]