How to use modulescripts?

I have read a few posts about this and do understand them to some degree but I just want a clarification just to make sure I get it, are module scripts a way to store and organize functions/code to eventually call them in a regular script? or do they have other aplications as well?

Module scripts are actually a way to write Repeated Functions, that you use frequently in your code, so basically it follows the Don’t-Repeat-Yourself principal. You write it once in the module, then require what whatever script & then use it.

It can function similar to any other functions, except it helps you write OOP based systems too. A really simple example of module script:

-- Tables are store multiple values in one variable
    local my_functions = {}
    
    -- Add a functions to the table
    function my_functions.foo()
    	print("Foo!")
    end
    
    -- ModuleScripts must return exactly one value
    return my_functions

So from your script you can require it as

local my_functions = require(path_to_the_script)

my_functions.foo()

That would print “Foo” into the console, additionally you can also pass and accept arguements too just like normal functions do.

Sometimes I use ModuleScripts to store some data, like for example, once I made a Inventory system and had stored Item data in it in a table and then returned that, so I can access it from anywhere easily :slight_smile:

1 Like

Actually, you can explore more on the API Reference too

Hope It helped you :slight_smile:

1 Like

thx for the answer, guess lll practice using them now

1 Like