Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I define variable in function as local in lua

Tags:

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.

like image 228
Samuel Avatar asked Aug 29 '26 00:08

Samuel


1 Answers

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).

like image 68
nonchip Avatar answered Sep 02 '26 12:09

nonchip