Lua - Namespaces



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 - Using namespaces

Consider the example shown below −

main.lua

-- Allow addition to namespace
Distance = Distance or {} 

-- create a function onedim within namespace Distance
function Distance.onedim(start, stop)
   return (start > stop) and start - stop or stop - start
end

-- create a function twodim within namespace Distance
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

-- call onedim function of Distance namespace
print(Distance.onedim(5,10))

-- call twodim function of Distance namespace
print(Distance.twodim({5,10},{10,20}))

Output

When we run the above code, we will get the following output−

5
11.180339887499
Advertisements