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

How to use 'return' in function?

local Fruittilium = game.Workspace.Fruittilium
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
Mouse.Button1Down:connect(function()
    if Mouse.Target == Fruittilium then
    print("you clicked it")
    local Fruit = Fruittilium:Clone()
    Fruit.Parent = game.Workspace
    Fruit.Name = "A Copy of Fruittilium"
         --  I want to return this 'vector3.new(Mouse.Hit.p)'
end
end)

So how do I use 'return' to return that value?

2 comments

0

You can put a variable before you connect the even then assign the value when the event is fired. How / where will this value be used?

0

Let me get you a full explanation once I'm st my desk

1 answer

✓ Accepted answer

Unfortunately, returning values from an event callback is possible, but useless.

This is because your callback function is being called by Roblox, who doesn't expect, or simply doesn't care whether you return values or not. It will just discard them.


Upvalues

Thankfully there is a way around this. What you can do instead is use "upvalues". That sounds like a whole new concept, but the truth is you've probably already used them before without knowing what they were called. Upvalues are variables that are declared prior to your function, in an upper scope. For example:

local tool = script.Parent

local selection


tool.Equipped:connect(function(mouse)
    local user = tool.Parent
    
    mouse.Button1Down:connect(function()
        -- 'selection' here is an upvalue, because it was declared
        -- outside of the current function.
        selection = mouse.Target
        
        -- Note that 'user' is also an upvalue here.
    end)
    
    -- 'selection' is an upvalue in this scope as well.
end)

game:GetService("UserInputService").InputBegan:connect(function(input, processed)
    -- Destroy selection upon pressing the delete key on the keyboard.
    
    if not processed then
        if input.KeyCode == Enum.KeyCode.Delete or
	    input.KeyCode == Enum.KeyCode.KeypadPeriod then
            -- Make sure the selection exists.
            if selection and not selection.Locked then
                selection:Destroy()
            end
        end
    end
end)

Conclusion

By setting and getting upvalues from within your functions, you can send information around without having to rely on returning values.

Anyway, I hope this helped. If it did then please be sure to accept, and optionally upvote, my answer. It helps both of us. ;) If you need anything else, you need only ask.

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