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 pcall?

I want to protect my calls in case something goes wrong the whole game wouldn't be broken, but how do I get the results from the functions? For example:

function randomstuff()
a = pcall(math.random,1,100)
if a then
 print([The result])
else return false
end
end

How would I get the results from the pcall?

A more pratical use would be:

function safeaddvalue(parent,name,value,add)
	a = pcall(value.Value = value.Value + add)
	if not a then
		b = Instance.new("NumberValue",parent)
		b.name = name
		b.value = add
		return false
	else return true
	end
end

My temporary solution:

function randomstuff()
	a = pcall(b = math.random,1,100)
	if a then
 		print(b)
	else return false
	end
end

Is it the correct way to do it? if not, what is?

1 comment

0

You're assigning the result to the variable 'a' in your first example.

1 answer

✓ Accepted answer

Your code is not wrong at all. The only thing you misinterpreted is that pcall will:

-Return true + all returned arguments from the function IF the function did not error -Return false + an error message (as second argument) if the function did error.

In other words:

Ok, ReturnValue = pcall(math.random, 1,2)

ReturnValue is the actual value returned from math.random, OK is true as this won't crash.

Want a cooler solution which immediately retrieves the second argument? Sure! We have the select function for that.

ReturnValue = select(2,pcall(math.random,1,2))

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