Skip to content

Namespaces Guide

Maurits edited this page Aug 26, 2016 · 5 revisions

Namespaces

The main purpose of namespaces within SIMPLOO is to categorize classes in their own global table structure. This prevents classes from multiple authors accidentally overwriting each other because they have the same name.

Behavior

When you declare a class in SIMPLOO, the default behavior is to store a reference to this class as a global variable, so that you can always create a new instance of this class from any random location. A class named "Dog" would literally be stored as _G["Dog"] and calling Dog.new() would invoke the new function on that variable.

When you declare a class inside a namespace, SIMPLOO will recursively create a global table for each segment inside the namespace name. For example, a Dog class placed in the world.animals namespace would create (if not yet existing) a table called _G["world"], then create inside of that a table called ["animals"], and you end up with a structure looking like _G["world"]["animals"]["Dog"]. This means that you can create a new instance of your class by calling world.animals.Dog.new(). When creating this table structure SIMPOO will never overwrite any tables, but only create new tables if they do not yet exist.

Declaring namespaces

You can either either declare a namespace inside the class name directly, or use the namespace keyword. When using the namespace keyword, all subsequently created classes will automatically be assigned to this namespace.

When you don't want to use a namespace, it's best to call namespace "" in your code to unset any previous namespaces that were set.

Using namespaces

Having to type the full namespace whenever you want to use a class can be annoying and make your code look messy. For this reason we added the using and as keywords which allow you to create an alias for a full class namespace declaration. This function creates the alias by changing the function environment of all your class methods, so it will not exist outside of these methods. The alias will automatically be assigned to all subsequently created classes until you call the namespace keyword again.

Examples:

namespace "world.city"

using "world.animals.Dog"

class "House" {
    createPets = function() Dog.new() end;
}
namespace "world.city"

using "world.animals.Dog" as "Snuffy"

class "House" {
    createPets = function() Snuffy.new() end;
}

Or use all classes inside a namespace;

namespace "world.city"

using "world.animals.*"

class "House" {
    createPets = function() Dog.new(); Horse.new() end;
}

Clone this wiki locally