Search code examples
lua

Should I define variable in function as local in lua


for example

function foo1()
    local i=10 --or just i=10
end 

The variable i is not visible out of the function. So should I declare it as local explicitly. Or It's already a local variable.


Solution

  • in Lua, every variable that's not explicitly declared local (except for arguments, because they are upvalue locals created implicitly by the VM) is a global, so doing this:

    function foo1()
      i=10
    end
    
    foo1()
    print(i) -- prints "10"
    

    is exactly the same as:

    _G["foo1"] = function()
      _G["i"]=10
    end
    
    foo1()
    print(i) -- prints "10"
    

    which is bad. so you should declare it as:

    local function foo1()
      local i=10
    end
    
    foo1()
    print(i) -- prints "nil", so it's local
    

    EDIT: but mind the closure's upvalues. e.g. this:

    local function foo()
      local i=10
      local function bar()
        i=5
      end
      print(i) -- 10
      bar()
      print(i) -- 5
    end
    
    print(i) -- nil
    foo()
    print(i) -- nil
    

    EDIT 2: also, you should consider making your functions local, so they don't bloat the global table. just declare them as local function ......

    tl;dr: just make everything local unless you really have a good reason not to (=never), because that way you can't accidentally collide names. lua making everything global by default is a historical decision that's considered bad practice nowadays. one the reasons i like moonscript because it defaults everything to local (also the syntax is way nicer to me).