I’m currently writing a ModuleScript that contains various methods for various UI animations. For legibility purposes, I don’t want to call those methods via the traditional way of ModuleScript.Function(Parameter), as I would have to call it like this UiAnims.FadeIn(Instance), which isn’t very readable when skimming code quickly.
Instead I would want to call it like this: Instance:Function()
Much the same as to how you would destroy an instance: Instance:Destroy()
How would I go about doing this? Furthermore, how would I know what InstanceClass the method is being called on?
I’ve tried this so far:
--Script: Calls method(s) from ModuleScript
local UiAnims = require(game.ServerScriptService.UiAnims)
local ImageLabel = script.Parent
ImageLabel:UiAnims.FadeIn()
--ModuleScript: Method(s) that are called from Script(s)
local module = {}
function module:FadeIn()
print("Executing :FadeIn method on Instance")
end
return module
Yes. I want to be able to simply require the module script and then call the method on any instance that is a UI element, without needing to reference the moduelscript several times.
I pass a function as a callback in some of my modules. For example, in the Module Script:
-- I am Module Script game.ServerScriptService.UiAnims
local functionFromParent = {} -- a callback, will store a function hook from parent module
function m.setPlinthCallback(pFunc) -- set the callback
functionFromParent = pFunc
end
function doStuffThatRequiresCallback(pParam1, pParam2, pEtc) -- normal module code, doing its thing
functionFromParent(pParam1, "test", true) -- call the callback and pass the parameters that it expects
end
return m
And in the parent main module that invokes the module above:
myModule = require(game.ServerScriptService.UiAnims) -- module is loaded, but can't call parent functions in THIS module. So:
function theFunctionThatModuleNeedsToCallbackTo(pParam1, pStr, pParam3)
-- This function may be called by loaded modules by passing a reference to it
-- do stuff
end
myModule.setPlinthCallback(theFunctionThatModuleNeedsToCallbackTo) -- Tell it the callback function
To keep track of which InstanceClass, then, you could add it to the params when setting the callback.
You could make the class and call the methods (the anims) on the instances with something like:
local UIAnims = {}
UIAnims.__index = UIAnims
function UIAnims.new(instance)
local self = setmetatable({}, UIAnims)
self.instance = instance
return self
end
function UIAnims:FadeIn(duration)
-- Do your fading here
print("Executing :FadeIn method on Instance")
end
return UIAnims
With an example usage:
-- Usage
local UIAnims = require(game.ReplicatedStorage.UIAnims)
local ImageLabel = UIAnims.new(script.Parent)
ImageLabel:FadeIn(2)
–
This will create an object of the UIAnims class for the specified UIElement and you can then call methods on that object (such as FadeIn, or whatever other animations you want to add).