Lua - How can I get any return?

I am interested in capturing any return function format. for instance

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 ok 

I am creating a profiler that will overwrite functions using proxy functions, but I need to know the returned data, then check its type() and access accordingly, but the code shows that I can not access all 3 with one method . Whether there is a?

+5
source share
3 answers

If the maximum number of returns is known, use something like

 v1,v2,v3 = foo() 

but you won’t be able to determine if foo returned two or three, and the last returned zero.

A reliable solution is to collect all returns in the table:

 v = table.pack(foo()) 

Then vn contains the number of returned values, including all nils.

+8
source

Here is the version that works on any version of Lua 5.1 +.

 local function WrapAndInspect(Inspector, FunctionToCall) local function Inspect(...) Inspector(...) return ... end local function Wrapper(...) return Inspect(FunctionToCall(...)) end return Wrapper end 

What WrapAndInspect does, generates a function that will call that function, then passes its return values ​​to the second function that you provide. This function can do whatever processing you think is necessary for them. But the structure ensures that the return values ​​from the original function are passed as is.

Here's an option that does something similar, but instead of wrapping FunctionToCall , it returns a function that takes a function to be called (along with its parameters):

 local function CallAndInspect(Inspector) local function Inspect(...) Inspector(...) return ... end local function Caller(FunctionToCall, ...) return Inspect(FunctionToCall(...)) end return Caller end 

You can use this function for any specific function that you want to test.

+4
source

Below is a workaround for those who do not have access to table.pack . This seems simple to me, and it should work on lua 5.1 and higher - and possibly even on earlier versions of lua.

table_pack should work like table.pack

 function table_pack(...) return {n=select("#", ...), ...} end function foo() return 1, 2, 3 end local v = table_pack(foo()) print(vn) 
+3
source

Source: https://habr.com/ru/post/1241251/


All Articles