Search code examples
variablesscopeluaglobal-variables

lua variables scope


I am aware there are other similar topics but could not find an straight answer for my question.

Suppose you have a function such as:

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

For the aLuaTable variable inside the if statement, it is still local right?. Basically what I am asking is if I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?.

Additionally I read this definition for Lua global variables:

Any variable not in a defined block is said to be in the global scope. Anything in the global scope is accessible by all inner scopes.

What is it meant by not in a defined block?, my understanding is that if I "declare" a variable anywhere it will always be global is that not correct?.

Sorry if the questions are too simple, but coming from Java and objective-c, lua is very odd to me.


Solution

  • "Any variable not in a defined block is said to be in the global scope."

    This is simply wrong, so your confusion is understandable. Looks like you got that from the user wiki. I just updated the page with the correction information:

    Any variable that's not defined as local is global.

    my understanding is that if I "declare" a variable anywhere it will always be global

    If you don't define it as local, it will be global. However, if you then create a local with the same name, it will take precedence over the global (i.e. Lua "sees" locals first when trying to resolve a variable name). See the example at the bottom of this post.

    If I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?

    When your code is compiled, Lua tracks any local variables you define and knows which are available in a given scope. Whenever you read/write a variable, if there is a local in scope with that name, it's used. If there isn't, the read/write is translated (at compile time) into a table read/write (via the table _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"])
    

    Locals are lexically scoped. Everything else goes in _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