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

How can I get a ModuleScript to return a value?

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 comment

1

Just add a 'return' inside your ModuleScript's returned function.

2 answers

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

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.

2 comments

1

They can return functions. http://wiki.roblox.com/index.php?title=Module_scripts Look at the first example

0

So can it or can't it? And how would I fix my script?

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