Skip to content

2. Creating a Main Class

Tom O'Sullivan edited this page Nov 3, 2021 · 1 revision

Now that you have your ClassLoader project set up, you'll want to create a Main class.

To do this, you'll need to create a new package for your project, packages are created for each directory in the classes location. This means that if you create a directory at classes/dev/tomdotbat/test the package would be dev.tomdotbat.test. For information on how to correctly name your packages, refer to the Java documentation.

Now that you've created a package, (in this example we'll be using dev.tomdotbat.test) create a new Lua file in there for your Main class, we'll name ours main.lua. This means that to import your Main class we'd refer to it with the location dev.tomdotbat.test.Main.

Every file has its class name determined automatically, this is done by capitalising every letter that is preceded by an underscore before removing it. An example of this is test_class.lua, the class name would be TestClass.

With that out of the way, we can now make the contents of our Main class. Try using the following code to get you started:

local Start = Singleton() --Starts the definition of a singleton class.

local print = _G.print

function Start:Main() --Defines our Main method (this is case sensitive).
    print("Hello World!")
end

return Start --Returns the class to the ClassLoader, this cannot be removed.

You may notice a few things about this example:

  • Firstly, we're creating a Singleton instead of a Class, this is because our Main class should only be used to start things off, so we don't need to be able to create an instance of it with the Class:New() method.
  • The second thing that may stand out is how the print function is called. This because the ClassLoader environment is restricted to encourage localisation of global variables. This means that if you want to access a field from the global table you need to index _G. So print() turns to _G.print(), debug.getinfo to _G.debug.getinfo and so on.
Clone this wiki locally