Skip to content
This repository has been archived by the owner on Jan 10, 2025. It is now read-only.

Introduction to Classes

smokingplaya edited this page May 24, 2024 · 4 revisions

Lua is a good language, but he haven't a lot of cool things.
For example - easy class creation.
That's why we tried to implement simple class system in Lua.
Yes, it based on metatables.
This system is abstraction over metatables.
But let me better tell you how to work with it.

How to create yourown class.

Funeral is loading all lua files, that places in lua/classes/client, lua/classes/shared and lua/classes/server folder. So, first that you need to do - create .lua file in lua/classes/(state: client, shared, server).

For example we will be create "Human" class in lua/classes/shared/human.lua Paste this code (base of class):

local class = {}
class.name = "Human" -- Name of class' table in lua global table

function class:new(name)
  self.name = name
end

return class

So, now we have function Human:new(name) in lua global table. This system is familar to panel's define in Garry's Mod.

local new_human = Human:new("John")
print(new_human) -- output: [object Human]

And we can get class metatable.

print(new_human:GetClass()) -- output: [class Human]

It's awesome, right?

Static methods

Most object-oriented programming languages support Static methods.

Static method is a static method, i.e. a method that can be called without creating a new object,
this method is not associated with any object, but with a class.
That is, static method is a method that does not interact with the object in any way.

Okay, let's look at an example of how we can create static methods.
We'll take the already existing “Human” class we made above.

Let's create a table for static methods and variables.

class.static = {}

Now everything in this table will be static

Example of static variable:

-- static variable
class.static.HumanCount = 0;

-- on creating a new object of class Human adds one to static variable
function class:new()
  class.static.HumanCount = class.static.HumanCount+1
end

Example of static method:

function class.static.GetHumanCount()
   return class.static.HumanCount
end

print(Human.GetHumanCount()) -- output: => 0

-- or it could be this:

function class.static:GetHumanCount()
   return self.HumanCount
end

print(Human:GetHumanCount()) -- output: => 0
Clone this wiki locally