Lua-我如何获得退货? [英] Lua - How can I grab any return?
问题描述
我有兴趣获取函数的任何返回格式.例如
I am interested in grabbing any return format of a function. For example
function foo()
return 1
end
local result = foo() -- foo is numeric 1
function foo()
return {1,2,3}
end
local result1, result2, result3 = foo()
local result = foo() -- this is bad as result is `1` but `2` and `3` are lost
function foo()
return 1, 2, 3
end
local result = foo() -- foo is a table with all the numbers, that's ok
我正在构建一个探查器,它将使用代理函数覆盖函数,但是我需要知道返回的数据,然后检查它的type()
并进行相应的访问`,但是从代码中可以看出,我无法访问所有一种方法有3种情况.有吗?
I am building a profiler which will overwrite functions with proxy functions but I need to know the data returned, then check type()
of it and access accordingly` but from the code it can be seen that I am unable to access all 3 situations with one method. Is there any ?
推荐答案
如果知道最大的回报数,请使用类似的
If the maximum number of returns is known, use something like
v1,v2,v3 = foo()
,但是您将无法判断foo
返回的是两个还是三个,最后一个为nil.
but you won't be able to tell whether foo
returned two values or three, with the last one being nil.
可靠的解决方案是收集表中的所有收益:
The robust solution is to collect all returns in a table:
v = table.pack(foo())
然后v.n
包含返回值的数量,包括所有nil.
Then v.n
contains the number of returned values, including all nils.
这篇关于Lua-我如何获得退货?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!