Skip to content

Instantly share code, notes, and snippets.

@njligames
Last active May 16, 2018 15:00
Show Gist options
  • Save njligames/fdf0fd425dbee22505936f1f26e4f554 to your computer and use it in GitHub Desktop.
Save njligames/fdf0fd425dbee22505936f1f26e4f554 to your computer and use it in GitHub Desktop.
lua protected call
local function _xpcall(func, params)
assert((type(params) == 'table'), "input param must be a table")
status, err, ret = xpcall (func, debug.traceback, params)
assert(status, err)
assert((type(err) == 'table'), "return value must be a table")
return err
end
-- ERROR EXAMPLE
function f (...)
local arg=...
local a,b = arg[1], arg[2]
return {a + "b", "jim"}
end
function f2 (...)
local arg=...
local a,b = arg[1], arg[2]
return {a + b, "jim"}
end
local t
t = _xpcall(f2, {1,5})
t = _xpcall(f, {1,5})
function f (...)
local arg=...
local a,b = arg[1], arg[2]
return {a + b, "jim"}
end
status, ret, err = xpcall (f, debug.traceback, {1,5})
print ("status", status)
print ("ret", ret)
print ("err", err)
--[[
status true
ret table: 0x420650
err nil
]]--
-- ERROR EXAMPLE
function f (...)
local arg=...
local a,b = arg[1], arg[2]
return {a + "b", "jim"}
end
status, ret, err = xpcall (f, debug.traceback, {1,5})
print ("status", status)
print ("ret", ret)
print ("err", err)
--[[
status false
ret /Users/jamesfolk/Documents/lua_scratch_pad/main.lua:23: attempt to perform arithmetic on a string value
stack traceback:
/Users/jamesfolk/Documents/lua_scratch_pad/main.lua:23: in function 'f'
[C]: in function 'xpcall'
/Users/jamesfolk/Documents/lua_scratch_pad/main.lua:26: in function </Users/jamesfolk/Documents/lua_scratch_pad/main.lua:1>
/Users/jamesfolk/Documents/lua_scratch_pad/main.lua:1: in main chunk
err nil
]]--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment