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 "." :

1
2
function myNamespace.foo()
end

question :

myNamespace = {} Will this go in new file and then you require that file?

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

1
local foo = require "myfile"
views:1509 update:2011/10/5 21:23:48
corona forums © 2003-2011