Local vs. Global variables

Knowing the scope of variables is an important issue. When designing your code, you need to know what values are needed for which pieces of code.

Writing functions

Functions are usually receiving arguments, do something with them and returns maybe a number of return values. All this is involving variables, which is in most cases a mix of global and local values.

function dosomething (arg1,arg2)
  local a = "Arg 1: "..tostring(arg1)
  local b = "Arg 2: "..tostring(arg2)
  return a,b

This function has 4 local variables and is accessing 3 different global variables.

The local variables are:

  • arg1
  • arg2
  • a
  • b

The global variables are:
  • dosomething
  • tostring
  • print

Especially when it comes to global values, things are easily overlooked. The function name "dosomething" is also a global variable. If we would want it to be a local variable we would write: local function dosomething (arg1,arg2)

The local keyword will forbid any access on a variable outside of the scope of the variable.