Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Module function only works when I run the game?

Asked by
funyun 958 Moderation Voter
9 years ago

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

Log in to vote
1
Answered by
Wizzy011 245 Moderation Voter
9 years ago

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
Ad

Answer this question