Issues with looping module scripts

I want to print the cost of each weapon from module scripts.

My code

weaponsmodule = require(game.ServerScriptService.ModuleScript)
for i, weapons in pairs (game.ReplicatedStorage:GetChildren()) do
	print(weaponsmodule.weapons.cost)
end

It throws me this error

My module

local module = {
	["Sword"] = {
		cost = 100,
		damage = 50
	},
	["Gun"] = {
		cost = 1000,
		damage = 500
	}
}

return module

So I made a simple script

weaponsmodule = require(game.ServerScriptService.ModuleScript)
local weapon = game.ReplicatedStorage.Sword

	print(weaponsmodule.weapon.Name.cost)

It throws me this error

I put the name in a variable this time

weaponsmodule = require(game.ServerScriptService.ModuleScript)
local weapon = game.ReplicatedStorage.Sword
name = weapon.Name
	print(weaponsmodule.name.cost)

It throws the same error as the first try

Here this should work:

local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local WeaponModule = require(ServerStorage:WaitForChild("ModuleScript"))
local Weapon = ReplicatedStorage:WaitForChild("Sword")

print(WeaponModule[Weapon.Name].cost)

I optimized and changed some stuff so it looks more clean and more redeable.

  • Consider moving your stuff such as modules to ServerStorage instead of ServerScriptService since it’s more secure.
1 Like