Calling Module Scripts' Functions

Two Questions.

  1. Do ModuleScripts need to have a table? For example, you would put
    local MyFunctions = {}
    function printf()
    print’ran script’
    end

And on require, you’d require and call to the print function through MyFunctions.printf(). But do you really need the MyFunctions? Can’t you just do printf() after you loaded the function and not have to use a table?

  1. Module script as a global variable. For instance, have a module script, and only call to it once. Traditionally, you’d do local MyFunctions = require(yattayatta), but cant you do _G.MyFunctions?
1 Like

Modules basically store functions to a table, and whenever the module is called it returns the table of functions

1 Like
  1. Possible module ways:
local module = {}
function module.printf()
	print("ran script")
end
return module
function printf()
	print("ran script")
end
return {printf = printf}
  1. Yes, you can do it, just be careful. It needs time to load.
    Example:
_G.Func = require(script.ModuleScript)
_G.Func.printf()
2 Likes

u can just directly put an function inside module script without having the need of using tables

return function()
   print("hi")
end
local func = require(module)
func()

_G cant be trusted as there is an race condition that it is loaded or not but im sure u can have an workaround by wait until its loaded (bad practice tho). You have to make an script that already defines all the modules inside _G

repeat task.wait() until _G.MyFunctions ~= nil
1 Like

If it’s for a singular function, you can do the following:

local function addAB(a: number, b: number): number
   return (a + b)
end

return addAB

This will make it so that if you require the module and directly call it:

local addAB = require(path.to.module)

addAB(1, 2)
-- returns 3

However, if you’ve got multiple functions that you need to be public then yes, they need to be children of a parent table returned by the module script.

I tend to avoid using global variables, it’s better to declare everything as a local variable and it’s also much faster due to Lua’s precompiler.

1 Like

If I were to load example 2, how would I structure the module script to support multiple functions? (With the returning process)

Edit: answered by @Midnightific , thanks!

1 Like

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