Differences between pcall, and xpcall


  • pcall(func, arg1, …) returns: boolean, status (string, err message)

    local function test()
    	
    	local a = 1/nil
    	print(a)
    	
    end
    
    local success, status = pcall(test)
    
    if success then
    	print('success')
    else
    	warn(status)
    end
    
    Output:
    server.lua:2: attempt to perform arithmetic on global 'a' (a nil value)
    

    **xpcall(f, err)
    xpcall is similar to pcall, except that you can set a new error handler, example:

    local function test()
    	
    	local a = 1/nil
    	print(a)
    	
    end
    
    local function err_callback(err)
    	return print("ERROR:", err)
    end
    
    local success = xpcall(test, err_callback) -- you can also change err_callback with 'warn' to print out a warning message instead of a print.
    
    print(success)
    
    Output:
    ERROR: server.lua:2: attempt to perform arithmetic on global 'a' (a nil value)
    false
    

    In all they are not so different but work in different ways. Which ever way you want to test your code is up to you. I prefer xpcall only because its more cleaner to me.


  • Why return print("ERROR:", err)? print has no return value so that's kinda pointless

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.