Why? Lua docs talk about how all variables are global unless specified otherwise, but that simple test would suggest otherwise.. unless I'm very confused about how it uses the word "global" (I suspect this is the case). How do I get one function to see another function's variables?
var hasn't been assigned yet because you haven't called foo(). The function keyword only defines the function - it doesn't actually execute the code inside of it until you call the function. You need to put foo() above print(var).
Also, you probably shouldn't use global state unless you have good reason to. Better to have foo() return "bloop" than set the value of a global variable.
Why? Lua docs talk about how all variables are global unless specified otherwise, but that simple test would suggest otherwise.. unless I'm very confused about how it uses the word "global" (I suspect this is the case). How do I get one function to see another function's variables?
global means it exists in every file and every scope (unless that scope or file has a local defined, in which that local of the same name will be used in the scope)
it is nil because foo() has not been executed. try this:
This doesn't store a (global) variable, but it allows you to 'pass' information.
Do you recognise when the world won't stop for you? Or when the days don't care what you've got to do? When the weight's too tough to lift up, what do you? Don't let them choose for you, that's on you.
I always found it strange that Lua uses global variables by default. I use "local" before like 90% of all variables. It would save plenty of characters to have locals by default and explicitly write "global" when you want global variables. Then again, only for local variables does it matter where you define it, so I guess it makes some sense.
T-Bone wrote:I always found it strange that Lua uses global variables by default. I use "local" before like 90% of all variables. It would save plenty of characters to have locals by default and explicitly write "global" when you want global variables. Then again, only for local variables does it matter where you define it, so I guess it makes some sense.
Yeah, exactly. Python does it the other way around and had to introduce the "nonlocal" keyword to be able to assign to "upvalues". It seems nice, local by default, but it gets messy if you try to make use of scoping.
JavaScript does it like Lua (with "var" instead of "local"), except that it's pretty much broken there. Déjà Vu uses Lua-style scoping as well.
var = 1
inc_var = function ()
var = var + 1
end
print(var)
inc_var()
print(var)
Typically, if you have data outside functions, then they certainly mean something in your "world". Then, they probably belong to the state of some world element, thus are eg a field in a table (a table used as "object"). Even more if you manipulate it.