How do I compare the results of two functions with multiple return values in one expression?

Viewed 629

I have written a test utility function aequals (assert equals) that expects an actual result and an expected result as arguments. I use it like this:

aequals(fib(8), 21);

But now I have a function with multiple return values:

function stuff() return 1,2,3 end

I want to check its function by either checking it all together:

aequals( stuff(), {1,2,3} );

but this does not work because only "1" is left on the stack for aequals.

Or at least one after the other:

aequals( stuff()[1], 1 );
aequals( stuff()[2], 2 );
aequals( stuff()[3], 3 );

but this gives a syntax error, because stuff returns a tuple, not an array/table.

I tried to fix this using the array-constructor, which supposed to make a tuple into an array/table.

aequals( {stuff()}[1], 1 );

why this is a syntax error I can not understand.

I circumvented this by defining helper functions which I am sure are already in Lua, if I only knew where to look:

function arg0(a,b,c) return a end;
function arg1(a,b,c) return b end;
function arg2(a,b,c) return c end;

aequals( arg0(stuff()), 1 );

While this works it is quite cumbersome and it would be so much nicer to have the whole check in one line... but how?

1 Answers
function stuff() return 1,2,3 end

aequals( stuff(), {1,2,3} );

Used like this, the list returned by stuff() will be reduced to the first element, because stuff() is not the last expression in that expression list.

You could swap the table and stuff() to circumvent this in a simple manner.

aequals({1,2,3}, stuff())

Or use tables as suggested by Egor's comment.

From Lua 5.3 Reference Manual 3.4 Expressions

Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see §3.3.6), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values.

Related