Make print() work versus tuples

print(pcall(f)) only prints the first element of the tuple returned from pcall.

To print the second element I need to write:

a,b = pcall(f)
print(b) --> 'some text'

print(pcall(f)) should print the entire tuple.

This arose in the context of me trying to figure out how to correctly invoke DataStore:GetAysnc() using a pcall to actually get a result back.

It already does that… It’s a feature of Lua itself, if multiple values are returned on the stack and the call is placed in e.g. a function, they’ll pass all stack values to the function you call as expected (well, you get the idea).

true 1 2
false print(pcall(function() return 1, 2; end)); print(pcall(function() error('ERROR'); end));:1: ERROR```
1 Like

Also be aware that if b is nothing (void function or not returning anything, not even nil) then you’ll only see a. That might be the reason why you didn’t realise it already works this way.

Because then it will basically be print(a,b) with b is nothing, so print(a)

3 Likes

Does it not already?
I swear it does.

One of those times it’s extremely annoying that Lua has no explicit nil. :stuck_out_tongue:

Cool.

I think that answers my other question too.

Not sure if I’m confused or you’re wrong-ish (pls no think le me le offensive), but:

local function test() return "hi",nil end
print(nil) --> nil
print("hi",nil) --> hi, nil
print(test()) --> hi, nil
print(test(),1) --> hi, 1
print(1,test()) --> 1, hi, nil

Doing print(a,b) will always result in 2 things being printed, although one/both can be nil.

I formulated it a bit shorthand because there’s not really a good way to simulate it with Lua statements. What I meant was: if the function doesn’t return anything (also no return nil), then b will be empty and the result would be equivalent to print(a) instead of print(a,b).

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.