Issues with pcall()

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I’d like to use a pcall() to call a function that might error, but I don’t want to re-write it as an anon function everytime. Instead of returning the desired result, I’m given an error that says “Attempt to call a number value”

Here’s 3 options that I’ve gone through so far:

#1 is the one I’d like to use the most

function OnClick()
	local success, result = pcall(AddNumbers())
	if not success then --success is false
		error(result) -- prints "attempt to call a number value"
	else
		print(result)
	end
end

function AddNumbers()
	return 1 + 1
end

#2

function OnClick2()
	local success, result = pcall(function()
		 AddNumbers()
	end)
	if not success then
		error(result)
	else --pcall is successful
		print(result) --prints nil
	end
end

function AddNumbers()
	return 1 + 1
end

#3, this is the option I’d like to avoid the most

function OnClick3()
	local success, result = pcall(function()
		 return 1 + 1
	end)
	if not success then
		error(result)
	else --pcall is successful
		print(result) --returns 2
	end
end

--function AddNumbers()
--	return 1 + 1
--end

1st option should work if you remove the () after AddNumbers because otherwise you call the AddNumbers function instead of referencing it:

function OnClick()
	local success, result = pcall(AddNumbers) --Like this
3 Likes

Oh that’s an easy fix! Thank you!