Lua "require" with global "local"?
Clearly I have some mixed up, but I figured that by using something like this in "main.lua":
local module = require("module")
local var = "I should be global?"
printthis()
with module.lua containing something like:
function printthis()
print(var)
end
that printthis(var)
would work fine, because now the module.lua code is inside main.lua, no? Instead, printthis has no idea what var
is. I read it's good practice to use "local" on Lua variables when possible, but in this case, do I have to make var
global or is there开发者_开发技巧 a way for module.lua's printthis()
function to read var
properly?
No. That's not at all how it works.
The Lua interpreter provides one global table, referred to as _G normally, unless you're doing something kinky.
function printthis()
print(var)
end
This translates to, in reality
_G.printthis = function()
_G.print(_G.var);
end
And your code in main is equal to
local module = _G.require("module")
local var = "I should be global?"
_G.printthis()
But when you call printthis
- where did _G.var
get set? Nowhere. So the variable is nil, like all other accesses to a table where there is nothing at that key.
It might be inconvenient, but it's a much better idea in the long run to pass arguments than to set global variables instead. Once you come to change anything about the program, it's going to be completely impossible to make any changes, as the logic has no structure and you have no idea what happens where without reading every single line of code and understanding it at once. In addition, you can only use each key in one place, because it's a global table- so I sure hope nobody else wanted to use "var" as a variable name and you don't mind your code silently failing because you got a global name wrong.
The other two answers gloss over an important thing: lexical scoping.
This means, roughly, that code can access local variables that are defined where the code is defined. That probably sounds vague, so I'll give an example:
local cheese = 'sandwich'
print(cheese) -- prints sandwich
do -- this begins an anonymous block
local cheese = 22
print(cheese) -- prints 22
end
print(cheese) -- prints sandwich
So what we have here is two different variables: the outer one is "shadowed" by the inner one.
Now, onto functions:
do
local hotdog = 'hot'
function nonsense()
print(hotdog)
end
end
print(hotdog) -- prints nil, since there is no variable called hotdog here
nonsense() -- prints hot
Functions can see the local variables from where they are defined, not from where they are called. This is very important and very useful, once you get the hang of it.
I'm no expert in lua, but shouldn't var
be passed as variable. Something like this:
function printthis(var)
print(var)
end
You're missing your var
in function header. And you're passing your var
in main.lua
as an argument to printthis()
function.
精彩评论