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

How can I get a ModuleScript to return a value?

Asked by
Zerio920 285 Moderation Voter
9 years ago

I've got this simple child-picker in one ModuleScript:

function pick(model)
    local children = model:GetChildren()
    local number = math.random(1,#children)

    local child = children[number]
end

return pick

I'm not sure how to get this to return the child that's chosen, for other scripts to use. For example, I've got another Module Script which makes use of this:

local pick = require(game.Workspace.Pick)

function play(obj)  
    pick(game.Lighting.Sounds)

    if pick.Name == obj.Name then
        local file = pick:Clone()
        file.Parent = obj
        file.Pitch = 0.3 + math.random()
        file:Play()
    else
        pick(game.Lighting.Sounds)
    end
end

return play

I thought returning pick would also contain the child, but I guess not. Any help?

1
Just add a 'return' inside your ModuleScript's returned function. Muoshuu 580 — 9y

2 answers

Log in to vote
3
Answered by 9 years ago

Try returning something with the function in the Module script, and using it in your script.

For example:

function pick(model)
    local children = model:GetChildren()
    local number = math.random(#children)

    local child = children[number]
    return child;
end

return pick

Now in the other script, just saying 'pick(something)' won't work because you're trying to get it to work as a non-void function.

local pick = require(workspace["Pick"])

function play(obj)  
  local child =  pick(game.Lighting.Sounds)
    if child.Name == obj.Name then
        local file = child:Clone()
        file.Parent = obj
        file.Pitch = 0.3 + math.random()
        file:Play()
    else
       child = pick(game.Lighting.Sounds)
    end
end

return play

Ad
Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

EDIT: You can return a simple function. You can do it this way if you want, anyway (especially if there's a chance you might be needing multiple functions in the future)

Modules can return tables. The idea is that you use a module like this:

local module = require(game.ServerStorage.MyModule)

local blah = module.doThing( myStuff )

Since require just gives whatever the ModuleScript returned, the ModuleScript should look something like this:

function myFunc( stuff )
    print(stuff)
    return stuff * stuff
end

mymodule = {
    doThing = myFunc
}

return mymodule

If you want to be able to use a function defined in a module, you just have to put it in the table returned by the module.

1
They can return functions. http://wiki.roblox.com/index.php?title=Module_scripts Look at the first example DigitalVeer 1473 — 9y
0
So can it or can't it? And how would I fix my script? Zerio920 285 — 9y

Answer this question