我的代码(psuedo)
function foo(cmd)
return load(cmd) --Note that this could cause an error, should 'cmd' be an invalid command
end
function moo()
return "moo"
end
function yoo(something)
something.do()
end
cmd = io.read() --Note that a syntax error will call an error in load. Therefore, I use pcall()
local result, error = pcall(cmd)
print(result)
此代码看起来没问题,并且有效,但我的问题是如果我输入moo()
那么result
将只显示命令是否在没有错误的情况下执行(如果命令调用错误,error
将有其价值。)
另一方面,如果我想致电yoo()
,我将无法从中获取返回值,因此我希望pcall()
true
/ false
(或除pcall()
之外的任何其他方式)
是否有另一种方法可以调用moo()
,获取返回值,还能捕获任何错误?
注意:除了try catch
/ pcall
之外,我找不到任何xpcall
等效内容。
答案 0 :(得分:0)
有点过时,但仍然没有正确答案......
您要找的是load()
和pcall()
load()
将输入的字符串cmd
编译成可以执行的内容(函数)。pcall()
执行load()
这两个函数都可以返回错误消息。从load()
获取语法错误说明,从pcall()
function moo()
return "moo"
end
function yoo(something)
something.do_something()
end
cmd = io.read()
-- we got some command in the form of a string
-- to be able to execute it, we have to compile (load) it first
local cmd_fn, err = load("return "..cmd);
if not cmd_fn then
-- there was a syntax error
print("Syntax error: "..err);
else
-- we have now compiled cmd in the form of function cmd_fn(), so we can try to execute it
local ok, result_or_error = pcall(cmd_fn)
if ok then
-- the code was executed successfully, print the returned value
print("Result: "..tostring(result_or_error));
else
-- runtime error, print error description
print("Run error: "..result_or_error)
end
end