
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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