How do I return an object with it's own set of functions

Hey, so I’m making an AI module for a game, and I have a function to create a new AI. I would like to return the AI & have a set of functions added to that AI.

An example of what I mean is this:

-- Server Script
local AI = require(script.AI)
local NewAIEntity = AI.new()
NewAIEntity:EquipCurrentWeapon() -- Would equip their weapon or something
-- Module
local Module = {}
Module.AIFunctions = {}
Module.new = function()

    return game.ServerStorage.AITemplate:Clone() -- Would also return a list of functions if you know what I mean
end)
Module.AIFunctions:EquipCurrentWeapon = function(self)
     self.Humanoid:EquipTool(self.Backpack:GetChildren()[1])
end)

How would I make the server script work correctly & have the function of AIFunctions be put into the AITemplate? I think it has something to do with metatables, but I’m unsure how to do that correctly, if someone could explain it or idk, that’d be helpful.

PREFACE: I’m making the assumption that you have a basic of metatables and metamethods

You can use a wrapper for this, you could simply make a blank table whose __index is the object but that will cause some issues when you try to call a function that belongs to the instance, so we have to take some other precautionary measures so we don’t have to pass the object manually every time:

function module.new()
    local instance = game.ServerStorage.AITemplate:Clone()
    local aiFunctions = {} -- fairly certain you'd have to define your table that handles the AI methods here, things that aren't related to the instance
    local meta = {
        __index = function(tbl, key)
				if type(instance[key]) == 'function' then -- this first check handles methods and functions that are inside of the instance itself
					return function(tbl, ...)
						return instance[key](instance,...)
					end
				else
					return instance[key]
				end
			end;
			__newindex = function(tbl, key, value) -- this handles assigning properties, you can handle it however you want
				if instance[key] ~= nil then
					instance[key] = value
				end
			end;
        end;
    }
    return setmetatable(aiFunctions, meta)
end

Thanks, I was able to tweak it and make it work.

1 Like