Page 1 of 1

pcall Bug/Issue

Posted: Tue Jul 31, 2012 2:56 pm
by Dino2306
Hi everyone, I've got an issue using pcall in the following code:

Code: Select all

arg = "Non-code"

if arg then
	ok, res = pcall(assert(loadstring(arg)))
	if ok then
--		say(channel, "Code executed!")
	else
--		say(channel, "Error occurred: " ..res)
	end
end
The code is part of a command for my IRC-bot (This is why arg is hardcoded here, and say, is commented.)

When running this code, arg is executed in the main chunk, and thus crashing löve.
Running any 'correct' code works fine, I.E. "print('Hello world!')"
The issue is that pcall is being 'faulty' ; when correct code is ran, the ok and res variables are 'returned' by pcall however.

Does anybody know what I did wrong, and how I can correct my error? :(

Re: pcall Bug/Issue

Posted: Tue Jul 31, 2012 3:49 pm
by Boolsheet
pcall's fine. It's assert that throws the error. I suggest using the term "error" for Lua errors because "crash" can be interpreted as an abnormal termination of the LÖVE application.

loadstring returns the compiled chunk as a function if it succeeds. If it fails, it returns:
nil, error_as_string

assert returns all passed arguments on success, but it will call error directly on failure.

In your example, if loadstring fails, assert will get nil as the first argument and throw an error. If you do want to handle this without hitting the error handler, drop the assert and check with if-statements or include it inside the function that will be passed to pcall.

Code: Select all

arg = "Non-code"

if arg then
	local chunk, err = loadstring(arg)
	if not chunk then
		-- say(channel, "Could not load code: ".. err)
	else
		local ok, res = pcall(chunk)
		if ok then
			-- say(channel, "Code executed!")
			else
			-- say(channel, "Error occurred: " ..res)
		end
	end
end

Re: pcall Bug/Issue

Posted: Tue Jul 31, 2012 3:57 pm
by Dino2306
Boolsheet wrote:--snip--
Thank you very much :D

Re: pcall Bug/Issue

Posted: Tue Jul 31, 2012 8:03 pm
by bartbes
Also, you were using pcall wrong, you were feeding it the result of assert. Do stuff like this:

Code: Select all

function_that_will_error(with, some, args)
-- turn that into
pcall(function_that_will_error, with, some, args)