Store Module Functions

I’m making a move handler, and I’d like to “pre-require” all the move modules, as repeating requires can impact performance. I’m wondering how to insert the value as a dictionary. Example:

for _,MoveModule in ipairs(MovesFolder:GetChildren()) do
	table.insert(MoveModules,require(MoveModule))
end

This code will result in an output like this

1  ▼  {
   ["Start"] = "function"
2  ▼  {
   ["Start"] = "function"

I’d like the index of the module function to be the moves name, which is the Kamehameha Wave or Afterimage.

["Kamehameha Wave"] = {["Start"]  = "function"}

Returning something along these lines is what I’m looking for. How do I do this?

You need to insert dictionary values? For what it’s worth, this is more a question for Google than for us, since it deals with fundamentals and you know how to word the question already.

dictionary[key] = value
dictionary[MoveModule.Name] = require(MoveModule)

If key is a string beginning with a letter or underscore, you can also do this.

dictionary.key = value

I’m not sure if I understand what the purpose of this code is. I don’t have something like this

local dictionary = {
   ["Stuff"] = nil,
}

Instead I just have this

local dictionary = {}

and want to insert this

["Kamehameha Wave"] = {["Start"]  = "function"}

So that I can reference the required module with

MoveModules["Kamehameha Wave"]:Start()
dictionary["Kamehameha Wave"] = {["Start"] = function() end}

The thing is that dictionary["Kamehameha Wave"] doesn’t exist yet.
Screen Shot 2021-05-15 at 10.05.51 AM
The move modules have the function Start(), I don’t have their Names in the dictionary with their Start function aswell; when I insert their functions, index returns with [1] and [2] when I need it to be Kamehameha Wave and Afterimage

Check my first post, this looks like what you want.

It’s difficult using dictionaries though, as dictionary[MoveModule.Name doesn’t exist yet. All I have is a blank table. If I were to use that method I’d have to hardcode each move name into the dictionary which isn’t optimal, as I’m trying to go organized and easy to add stuff; at the cost of complex systems.

Actually, that’s how you insert items into a dictionary, since as you know table.insert won’t do dictionaries. Give it a go, let me know if it errors.

1 Like
local MoveModules = {}

for _, MoveModule in ipairs(MovesFolder:GetChildren()) do
	MoveModules[MoveModule.Name] = require(MoveModule)
end

You can access the modules as MoveModules["Kamehameha Wave"], etc.

Mark Jarod as solution, I didn’t see he already posted this basically. Use this method, though. It’s worked for me many times.

1 Like

Exactly what I was lead to by Jarod, but thank you! Had no idea how to insert dictionary values.