3

example

function func1()
 return 1,1,1,1
end

table = {}
table = func1()

print(table)

I don't want to do

 function func1()
  return {1,1,1,1}
 end

because the function im working with is already defined and I cannot modify it.

the desired output is

1 1 1 1

but this is not the case; it only returns the first value that the function returned.

How can I make this possible? Sorry for the bad formatting; this is my first time asking a question.

Also, I'm pretty sure the table is equal to an array? so sorry for that as well.

EDIT I don't know the number of arguments either.

1 Answer 1

8

A function that returns multiple results will return them separately, not as a table.

Lua resource on multiple results: https://www.lua.org/pil/5.1.html

You can do what you want like this:

t = {func1()} -- wrapping the output of the function into a table
print(t[1], t[2], t[3], t[4])

This method is will always get all of the output values.


This method can also be done using table.pack:

t = table.pack(func1())
print(t[1], t[2], t[3], t[4])

by using table.pack you can discard nil results. This is can be helpful to preserve a simple check of the number of results using the length operator #; however it comes at the cost of no longer preserving the result "order".

To explain further, if func1 instead returned 1, nil, 1, 1 with the first method you receive a table where t[2] == nil. with the table.pack variation you will get t[2] == 1.


Alternatively you can do this:

function func1()
 return 1,1,1,1
end

t = {}
t[1], t[2], t[3], t[4] = func1() -- assigning each output of the function to a variable individually 

print(t[1], t[2], t[3], t[4])

This method can allow you to pick and choose where outputs go or if you want to ignore one you can simply do:

 t[1], _, t[3], t[4] = func1() -- skip the second value 
Sign up to request clarification or add additional context in comments.

2 Comments

I recommend t = table.pack(func1()) instead of t = {func1()} because then you can query the number of elements in the table with t.n (#t won't work if there are “holes”).
@HenriMenke added the table.pack variation to the answer, I still feel it can be a confusing result if you do expect internal nil values. in what i added to my answer, table.pack does not persevere the result. if the second result is nil then with table.pack the table you get has a t[2] that is not nil but is instead the value of result 3, and now t[3] is the value of result 4. if more then 1 result can return nil, table.pack makes it impossible to interpret the result

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.