Local and Global Variables

From PZwiki
Jump to: navigation, search
Language policy Language: [[::Local and Global Variables|English]]


There are two types of variables in Lua: local and global. So far, these tutorials have used only global variables (unless otherwise specified). Global variables are available to the whole program. Local variables are available inside the chunk they were created. See this example for further clarification:

for i  = 1, 3 do
local l = i*i
g = i*i
print(l, g)
end

print(l, g)

The global variable 'g' continues to exist outside the loop, while local 'l' is discarded. As can be seen, local variables can be specified using local. Local varibales only exist inside their 'chunk' or lower chunks, such as nested if statements. Chunks refer to a sequence of statements, such as inside an if statement, loop or function. See this example:

i = 4

if i > 3 then
 local v = "V"
 print(v .. " is available")
       if i/2 == math.floor(i/2) then
       local v2 = "v2"
       print(v  .. " is available in lower chunks too")
       print(v2 .. " is available as it was created in this lower chunk")
       end
 print(tostring(v2) .. " but is not available in a higher chunk")
end

It is considered good practice to avoid using global variables where possible. It makes code is easier to read (as you can see the scope of each variable used, i.e. the chunks it is used in), it clutters namespace and makes it easier to confuse common ones (such as 'player', 'x' or y') and could create problems where different parts of the program try to access a global simultaneously. Local variables allow you to bypass this problem.

One useful thing you can do with local variables is to make a copy of a global variable inside a chunk where it is needed. This preserves the global variable from any changes.

playerHealth = 100

function damageRecieved(damage)
local playerHealth = playerHealth
playerHealth = playerHealth - damage
print(playerHealth)
end

damageRecieved(25)
print(playerHealth))

The 'local v = v' can be a useful snippet to have.

Summary

  • Global variables scope is the whole program
  • Local varaible scope is only inside the chunk it was created (and any lower chunks)
  • Where possible, local variables should always be used
  • local v = v is a useful way to use the value of global variables while preserving them