How to make a namespace in Lua programming?


A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it.

In simple words, a namespace is a class of elements in which each element has a unique name to that class. It is used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

In Lua, there’s no such thing as a namespace. Despite not providing support for the same, the official documentation mentions that, “It is sometimes nice to organize your code into packages and modules with namespaces to avoid name clashes and to organize your code”.

Since Lua doesn’t have an official namespace, we will have to create one by ourselves, and the way to do that is to make use of tables.

In the code shown below we are creating a namespace with two different functions and we can use them without having programming issues.

Example

Consider the example shown below −

 Live Demo

Distance = Distance or {} -- Allow addition to namespace
function Distance.onedim(start, stop)
   return (start > stop) and start - stop or stop - start end
function Distance.twodim(start, stop)
   local xdiff = start[1] - stop[1]
   local ydiff = start[2] - stop[2]
   local summer = xdiff * xdiff + ydiff * ydiff
   return math.sqrt(summer)
   end
print(Distance.onedim(5,10))

Output

5

Updated on: 19-Jul-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements