Pretty much I have a bunch of functions in a ModuleScript to function as a pseudo database, and I want to be able to reference the same-named variables in each differently-named function.
Is this possible? If so, how would I use some form of iteration to print the variable from each function? I’ve tried looking around but I couldn’t find anything. D:
This was the closest thing I found, though I’m not sure if it’s what I’m looking for.
Module scripts are formatted like tables in a script, but people use them so their scripts don’t get super long, or copy and paste.
Here’s an example: This is one script
Script
local module = {}
function module.A()
print("A")
end
function module.B()
print("B")
end
function module.C()
print("C")
end
for i,v in pairs(module) do
print(i,v) -- i is the name of the function, v will call the function
v()
end
Now for an example in a module script!
Module
local module = {}
function module.A()
print("A")
end
function module.B()
print("B")
end
function module.C()
print("C")
end
return module
Script
local module = require(game.ServerScriptService.ModuleScript)
for i,v in pairs(module) do
print(i,v) -- i is the name of the function, v will call the function
v()
end
Building off of @xuefei123’s post, you can also check the ‘type’ to ensure it’s actually a function. This is useful if your module is storing other fields too:
for k,v in pairs(module) do
if (type(v) == "function") then
-- 'v' is the function and 'k' is the name
end
end
Adding to the above, it’s worth noting that ModuleScripts are just SourceContainers, like Scripts, LocalScripts, and CoreScripts. This means that they don’t have functions ‘in’ them.
You might choose to return a table in the code you write in a ModuleScript. There may be functions in that table. If so, follow the advice above.
In any given ModuleScript, however, you might have written code to return a function, or a string, or a Part, etc.