Lua - Local Functions



Functions are first class citizens in Lua. Which means a function can be stored in variable, can be passed as an argument to a function or can be returned from a function. This features allows to define functions which are not global in scope. Such functions are called local functions or anonymous functions.

A local function is accessible only in the scope where it is defined. A local function helps in organizing code and improves encapsulation. It also helps in prevent naming conflicts.

Syntax

A local function can be defined using following syntax −

local function functionName(parameter1, parameter2, ...)
  -- Function body
end

Where

  • local keyword is used to define function as a local function.

  • function-name is name of the function and parameter1 to parameterN are arguments passed.

Example - Usage of Local function

In this example, we're showing creation of a local function.

main.lua

-- define an outer function
function outer()
   local localVar = 10

   -- define a local function  
   local function inner(x)
      return x + localVar
   end

   -- call the inner function within outer function body, prints 15
   print(inner(5)) 
end

-- call the outer function
outer()

Output

When the above code is built and executed, it produces the following result −

15

Example - Trying to use Local function globally causes error

In this example, we're showing creation of a local function.

main.lua

-- define an outer function
function outer()
   local localVar = 10

   -- define a local function  
   local function inner(x)
      return x + localVar
   end

   -- call the inner function within outer function body, prints 15
   print(inner(5)) 
end

-- try to call the inner function, error will be raised.
inner()

Output

When the above code is built and executed, it produces the following result −

lua: main.lua:15: attempt to call a nil value (global 'inner')
stack traceback:
	main.lua:15: in main chunk
	[C]: in ?

Advantages of Local Functions

  • Namespace Management − Using local functions, we can define functions with same names as those are present in global scope without causing any conflict with other part of the code. We can define libraries with local functions and can use them without worrrying about naming conflicts.

  • Encapsulation − We can create modular code by creating helper functions within functions or blocks where they are used instead of defining them globally.

  • Increased Readability − When we limit the scope of a function, it becomes easy to understand the function as per the scope and it improves code readability.

  • Performace Improvement− Although slight performance improvement, but accessing local function is generally faster than accessing the global function.

Advertisements