pcall Bug/Issue

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Dino2306
Prole
Posts: 3
Joined: Sat May 05, 2012 1:35 pm

pcall Bug/Issue

Post 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? :(
User avatar
Boolsheet
Inner party member
Posts: 780
Joined: Wed Dec 29, 2010 4:57 am
Location: Switzerland

Re: pcall Bug/Issue

Post 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
Shallow indentations.
User avatar
Dino2306
Prole
Posts: 3
Joined: Sat May 05, 2012 1:35 pm

Re: pcall Bug/Issue

Post by Dino2306 »

Boolsheet wrote:--snip--
Thank you very much :D
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: pcall Bug/Issue

Post 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)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 4 guests