Lua variable scope

I know that there are other similar topics, but I could not find a direct answer to my question.

Suppose you have a function, for example:

function aFunction()
  local aLuaTable = {}
  if (something) then
     aLuaTable = {}
  end
end

For the aLuaTable variable inside the if statement, it is still local. Basically what I ask is that I first define the variable as local, and then I use it again and again, any number of times it will remain local for the rest of the program’s life cycle, how does it work exactly?

In addition, I read this definition for Lua global variables:

Any variable not contained in a particular block is called global. Everything that is available globally is available to all inland areas.

?, , "" , , ?.

, , Java objective-c, lua .

+3
2

" ".

, . , . :

, local, .

, "" ,

local, . , local , ( Lua "" ). . .

, , , ?

, Lua , , , . , / , , . , / ( ) / ( _ENV).

local x = 10 -- stored in a VM register (a C array)
y = 20       -- translated to _ENV["y"] = 20

x = 20       -- writes to the VM register associated with x
y = 30       -- translated to _ENV["y"] = 30

print(x)     -- reads from the VM register
print(y)     -- translated to print(_ENV["y"])

. _ENV.

x = 999

do -- create a new scope
    local x = 2
    print(x)      -- uses the local x, so we print 2
    x = 3         -- writing to the same local
    print(_ENV.x) -- explicitly reference the global x our local x is hiding
end

print(x) -- 999
+9

aLuaTable if - ?

, ; , Java. , .

A local "stack" Java. , , , .

Java:

public static void main()
{
  if(...)
  {
    int aVar = 5; //aVar exists.
    if(...)
    {
      aVar = 10; //aVar continues to exist.
    }
  }

  aVar = 20; //compile error: aVar stopped existing at the }
}

"global" - , . Lua :

function MyFuncName()
  if(...) then
    local aVar = 5 --aVar exists and is a local variable.

    if(...) then
      aVar = 10 --Since the most recent declaration of the symbol `aVar` in scope
                --is a `local`, this use of `aVar` refers to the `local` defined above.
    end
  end

  aVar = 20 --The previous `local aVar` is *not in scope*. That scope ended with
            --the above `end`. Therefore, this `aVar` refers to the *global* aVar.
end

, Java , Lua, , , , .

+2

All Articles