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]