问题
So let's say I have a lua file, and at the top, I define a variable outside of any function, but I call it local
local x = 1
Is there any difference between that local x, and a global x?
回答1:
Yes, as it is local to the chunk that it is created in.
Lua handles a chunk as the body of an anonymous function with a variable number of arguments (see §3.4.11). As such, chunks can define local variables, receive arguments, and return values. Moreover, such anonymous function is compiled as in the scope of an external local variable called _ENV (see §2.2). The resulting function always has _ENV as its only upvalue, even if it does not use that variable.
Consider this example:
-- main.lua
require 'other'
print(x, y)
-- other.lua
local x = 5
y = 10
This will print out nil, 10
, since x
was local to the chunk, while y
was assigned as an upvalue for whichever environment the chunk was loaded in.
See also:
- §2.2 – Environments and the Global Environment
- §3.3.7 – Local Declarations
And note that the semantics of environments changed between Lua5.1 and Lua5.2:
- Lua 5.1: §2.9 – Environments
来源:https://stackoverflow.com/questions/40208092/local-variables-in-global-scope-lua