Object/Instance Style Data System

Hello!
I am currently working on a data system for a currently solo project.
I tried a few different styles, but after a few days I ended up with object style system.

(Currently) The code works as intended (I am fairly new at this so that is a miracle), but I just have a feeling like something is off with the way I implemented classes

----VARS----
--Modules
local typeModule = require(script.Type)
local appModule = require(script.Appearance)

local module = {
	
	["Apple"] = function()
		return {
			Name = "Apple"; -- Name of the object
			ClassName = "Fruit"; -- Name of the class
			Parent = nil; --Parent of the object
			Type = typeModule.TestType; --Used to determine object type (project spcific)
			Appearance = appModule.TestApp -- Used to determine the object appearance (project --specific)
		}
	end,
	
	
}

----END_VARS----
return module

In this case, I return a table using a function assigned to the class name using this function

function gameInstance.New(className : string)--Attempts to create and return an object from the --provided class name

	if not className or typeof(className) ~= "string" then error("Expected class name string got " .. typeof(className)) end
	
	--Check if class exists
	local class = classData[className]
	if not class then error("Unable to create Game Instance of class " .. className) end
	
        --Call class as a function
	return class()
end

If you have any tips for better implementation please share.
Or if this is fine let me know I guess.

Sorry if the post is a mess. This is my first one

The best way to replicate Object-Orientation in Lua is to use metatables to short-cricuit your “prototype” table with the methods. This is both the cleanest and memory-efficient implementation possible.

local Fruit = {}
Fruit.__index = Fruit

function Fruit.new()
	local self = setmetatable({}, Fruit)
	
	self.Status = "Tasty"
	
	return self
end

function Fruit:Eat()
	self.Status = "Consumed"
end

You can then wrap that constructor inside other constructors to mimic inheritance, however Type-Inference will spas out on you for applying metatables on top of metatables, so be careful.

local Apple = {}
Apple.__index = Apple

setmetatable(Apple, Fruit)

function Apple.new()
	local self = setmetatable(Fruit.new(), Apple)
	
	self.Type = "Granny Smith"
	
	return self
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.