1

When I have a function that return multiple values I can either store them in seperat values or use the {} operator to get an array.

To access the values I can either define a variable to store the value or access the array via array[index]. When using a temp var to print the value I code:

function myTest()
  return "abc", "def", "geh";
end

a = {myTest()};
v = a[2];
print(v);

which works very well. But when printing the "indexed array converted return value" from the function with

function myTest2()
  return "abc", "def", "geh";
end

print({myFunction2()}[2]);

nothing gets printed.

Can someone explain me why?

2 Answers 2

3

The form:

{myFunction2()}[2]

is not syntactically valid. I get an unexpected symbol error for that.

You can write it like:

({myFunction2()})[2]

and then it works as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

note that you can use luac -p <file.lua> to parse a Lua file for syntax errors without executing it (Useful when your workin on a system that silently drops syntax errors)
3

Just don't. When you want to immediately access the Nth return value of a function, use (select(N, ...)), which does not create a new table (and thus creates less work for the GC)

function myTest2()
  return "abc", "def", "geh";
end

print( (select(2, myFunction2())) );

Note that enclosing a list of values in () truncates it to the first value; this is necessary because select(N, ...) returns the Nth and all following values. (select(N, ...)) returns only the Nth value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.