Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

A function can be declared as local to limit the scope of the function. A function is global by default.

It's good practice to use local whenever possible to limit the scope of functions and variables to where they are needed. It allows for a flexible and modular approach in designing functions.

 Example of a global function

If you were to create a simple APP.lua file and add a function called APPadd like below:

function APPadd(a,b)
   local sum = a + b
   return sum
end

In main you can then call APPadd and get the sum:

 Example of a local function

In the same APP.lua file, now alter the function to be local.

local function APPadd(a,b)
   local sum = a + b
   return sum
end

return APPadd 

Note: the function is now local, but we have also returned the APPadd function to create a closure - the values of a and b will be persisted even after the outer function has finished executing.

Now in main, you can capture the closure in your require statement, and use it as if it were APPadd.

  • No labels