systemdebt
systemdebt

Reputation: 4941

Lua function picking local variable instead of global

I have a local iand a global i. Th efunction g is picking local instead of global.Why is that ?

i=30
local i=1
g = function() i=i+1; print(i)

Upvotes: 3

Views: 451

Answers (2)

1hunch1kill
1hunch1kill

Reputation: 520

I think the 'local' is misleading you. According to the concept Lexical Scope in lua, when a local variable is defined, it will affect the whole chunk. What is chunk? According to Programming in Lua:

Each piece of code that Lua executes, such as a file or a single line in interactive mode, is called a chunk

So the local variable, here is 'i', works in this file, no matter it is called in function or other place, and its priority is higher than global variable with same name in this chunk.

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80639

When you're doing

i = 30
local i = 1

you're defining a new global variable i with the value 1. This i will be treated as the global one throughout your script. To access the truly global i, you'd have to provide the environment (in this case, _G):

function g()
  _G.i = _G.i + 1
  print( _G.i )
end

To further explain what happens here, consider the following script named a.lua:

i = 30
local i = 1
function t()
    return i
end

return _G

Here, my truly global variables are i and t. The i used inside t() would be the local i = 1. To see it actually work, create a new file b.lua as the following:

local a = require "a"
print( a.i, a.t() )

and you'll see the output to be:

30  1

Upvotes: 3

Related Questions