HOWTO: Being Modular Without Using module()

The Lua module design is not the most friendly thing in the world to use. It uses magic environment manipulation which is confusing to new users.

I am going to show you another paradigm. I am going to call it a “namespace” but it is nothing more than a table.

This is how you create one:

myNamespace = {}

Notice it is not local. Keep that in mind when picking a name. To prevent collisions.

You now have something equivalent to a module that you can add functions and fields to.

Functions have 2 “variants”, the first is akin to a “static function” and is defined using the “.” :

function myNamespace.foo() end

This type of function will work like your module functions. And you call it using the “.” as well:

myNamespace.foo()

The second type of function is akin to an “instance method” and is defined using the “:”:

function myNamespace:bar() end

This type of function includes access to it’s enclosing namespace via a special identifier “self” (similar to “this”)

So we could call myNamespace.foo() that we just defined from within myNamespace:bar() as follows:

function myNamespace:bar()  
 self.foo()  
end  

to call bar we use the “:”

myNamespace:bar()

So to recap, we created a namespace that can be used anywhere in your application. If the Lua file containing the namespace definition has not loaded you can simply call require on that Lua file.

This is similar to a class, and indeed you can perform a copy on the table myNamespace to create additional instances if you so desire. Using self correctly will help ensure that you always are referring to the correct instance.
[import]uid: 846 topic_id: 11038 reply_id: 311038[/import]

question :

myNamespace = {} Will this go in new file and then you require that file? [import]uid: 48521 topic_id: 11038 reply_id: 40226[/import]

Where you put it is up to you. Put it in whichever file makes the most sense.

Certainly you can put it in a file and then require the file.

You can put several of them in one file, or spread 1 across several files.

This gives you the ability to organize your code in a way that works best for you.

if you want to use use require like this

local foo = require "myfile"  

then you will need to add

return myNamespace  

at the end of “myfile” [import]uid: 846 topic_id: 11038 reply_id: 40230[/import]