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

How to use 'return' in function?

Asked by 8 years ago
Edited 8 years ago

Please make your question title relevant to your question content. It should be a one-sentence summary in question form.
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?

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? User#5423 17 — 8y
0
Let me get you a full explanation once I'm st my desk lightpower26 399 — 8y

1 answer

Log in to vote
0
Answered by
Link150 1355 Badge of Merit Moderation Voter
8 years ago
Edited 8 years ago

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.

Ad

Answer this question