3

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Replace "chunk" with "block". A chunk is comprised of one block. But other syntactic structures create nested blocks, most notably function definitions. There are many more, including for, in which the control variables are locals inside the block. A local variable has a scope that runs from a point after it is declared to the end of the block in which it is declared.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.