Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Module function only works when I run the game?

Today, I started working on my first module script for basic math functions. So far, I have:

A function to validate data (To make sure that it's just an array of numbers) A function for summation and A function to get the average/"mean" of the data.

Here's the script:

local module = {}






module.valid = function(data)
	if type(data) == "table" then
		
		for _, v in pairs(data) do
			if type(v) ~= "number" then
				assert(false, "Data must only contain number values.")
				return false
			end
		end
		
		return true
	end
end






module.summation = function(data)
	local sum = 0
	
	if module.valid(data) then
		for _, v in pairs(data) do
			sum = sum + v
		end
	end
	
	return sum
end






module.average = function(data)
	if module.valid(data) then
		local sum = module.summation(data)
		local avg = sum/#data
		return avg
	end
end






return module

With this, I can call both the validation and the summation functions from my command line without having to start the game. However, when I do...

print(require(game.ServerScriptService.Math).average({1, 2, 3, 4, 5, 6}))

...I get this error:

19:58:51.390 - print(require(game.ServerScriptService.Math).average({3, 4,:1: attempt to call field 'average' (a nil value)

When I run the game, I can do the exact same command and get (3.5). Could someone explain to me what's happening here?

1 answer

✓ Accepted answer

With ModuleScripts, the different functions inside the module should be laid out as function module.FUNCNAME(argument) rather than module.FUNCNAME = function(arg). By changing the layout, your script worked for me.

Here's a copy of the fully changed code:

local module = {}

function module.valid(data)
    if type(data) == "table" then

        for _, v in pairs(data) do
            if type(v) ~= "number" then
                assert(false, "Data must only contain number values.")
                return false
            end
        end

        return true
    end
end

function module.summation(data)
    local sum = 0

    if module.valid(data) then
        for _, v in pairs(data) do
            sum = sum + v
        end
    end

    return sum
end

function module.average(data)
    if module.valid(data) then
        local sum = module.summation(data)
        local avg = sum/#data
        return avg
    end
end

return module

This discussion is preserved as it was. New answers, comments, and votes are closed.