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

Whats the difference between returning in a pcall and not returning in a pcall?

Asked by 4 years ago
Edited 4 years ago
    local S,E = pcall(function()
        DataStore:GetAsync(Player.UserId)
    end)

print(S,E) -- Prints true, nil
    local S,E = pcall(function()
        return DataStore:GetAsync(Player.UserId)
    end)

print(S,E) --Prints true, a Number if got 

So what I was wondering for datastores which one was better

and if its safe setting a IntValue based on E

if S and E then
    IntValue.Value = E
end

Also when should you return something in a pcall

0
You can never be too safe, if an error may be thrown at you, you want to make sure the thing called is protected and runs with a pcall AltNature 169 — 4y

2 answers

Log in to vote
0
Answered by 4 years ago

Use the return keyword when you want to pass information from your function (in this case a pcall). Do note that when you return from a pcall, the second parameter (E in this case) will either be an error message (if your pcall fails) or your return value (if the pcall succeeds).

In this case,

if S and E then
    IntValue.Value = E
end

The IntValue will only be set to E if it succeeds, which is the proper way to do it. Just make sure that what is being returned from the pcall is actually an integer value (if you are setting an IntValue to that return value).

Check out these articles for more information on datastores: https://developer.roblox.com/en-us/articles/Data-store

https://developer.roblox.com/en-us/articles/Saving-Player-Data

Ad
Log in to vote
0
Answered by
RubenKan 3615 Moderation Voter Administrator Community Moderator
4 years ago
Edited 4 years ago

Personaly i recommend using an extra variable outside of the pcall scope to prevent complicating things with returning a variable if it does error, by this i mean, not using return at all in a pcall. The reason it gets complicated is because pcall uses the 2nd argument for the return variable if it doesnt error, but places it to a 3rd variable if it does error. (even though usualy when you return something and it errors it wouldnt have returned something in the first place)

local Variable
local s,e = pcall(function()
    Variable = "this"..will.."error"
end)

if not s then warn(e) else
    --stuff with Variable
end

If you used return with pcall you'd have to do something like this

local s,e,returnValueOnError = pcall(function()
    return 2
end)

if not s then warn(e..returnValueOnError) else
    returnValue = e
--stuff
end

Answer this question