Hi,
I’m looking to check if a ModuleScript has a function in it before proceeding; I’ve seen this method:
However, it doesn’t seem to work.
Hi,
I’m looking to check if a ModuleScript has a function in it before proceeding; I’ve seen this method:
However, it doesn’t seem to work.
You can use pcall()
to achieve this. It takes a function, executes it and returns false if any errors happen in the function you passed to pcall()
. For example:
local module = require(SomeModule)
if pcall(function()
module:SomeMethod()
-- NOTE: This function is actually executed so keep that in mind.
end) then
-- Module has that function
else
-- Module doesn't have that function
end
Modules are tables, so treat them as such.
If I had a module with a function named Test, I could try to index the module using “Test” as the key. If it returns nil, then the function doesn’t exist. If the function exists, the function will be returned.
I would write out the code for illustrative purposes, but I’m on mobile right now.
If you have any questions, let me know. I hope this helps.
Modules are not tables, they are objects that return a value upon using a special function, require. A required ModuleScript will evaluate to what it returns. If you do not return a table, then you don’t have a table. Modules should not be treated as tables unless you are returning one.
That can be done without needing to call any function.
local module = require(TheModule)
local containsFunction = (type(module) == "table") and (type(module["FunctionName"]) == "function")
print(containsFunction)
What other applications are there for ModuleScripts beside returning a table of functions (and sometimes, variables)?
If the method you cited isn’t working, your module might be formatted awkwardly. Can we what you are returning?
Single-function returns, e.g. fastSpawn which returns a reusable function and not a table of functions or variables.
I sometimes use modules to implement custom classes.
return (function()
local object = {}
object.value1 = 38
object.value2 = "hello"
function object:getter1()
return self.value1
end
function object:setter1(v)
self.value1 = v
end
return object
end)
local constructor = require(module)
local object = constructor()
object:setter1("test")
print(object:getter1())
this feels like your overdoing oop just to get a little more info on functions but to each there own I like to keep things more simplified.