Multiple Results & Return

local function ReturnStuff_Func(Arg1,Arg2)
	return Arg1,Arg2
end

local function Func(Arg1,Arg2)
	print(Arg1,Arg2)
	local Arg1,Arg2 = Arg1 and Arg2 or ReturnStuff_Func('A','B')
	print(Arg1,Arg2)
	print(ReturnStuff_Func('A','B'))
end

Func(1,nil)

Output

nil 1
A nil

I don’t understand why Arg2 isn’t = ‘B’

You’re effectively doing nil or ReturnStuff_Func("A", "B"). The function returns two values: “A” and “B”, but the or logical operator expects only two operands, so Lua adjusts the number of returned values to one. As a result of this, the operation evaluates to “A” and Arg2 is given nil.

According to Programming in Lua : 5.1 : 5.1 - Multiple Results:

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions. These lists appear in four constructions in Lua: multiple assignment, arguments to function calls, table constructors, and return statements. To illustrate all these uses, we will assume the following definitions for the next examples:

1 Like

I read the link briefly, it doesn’t have anything on logical operator but I understand how returning values work.

So does this means that I can’t make

local Arg1,Arg2 = unpack(ReturnStuff_Func('A','B')) or Arg1

Work as I would like it to?

No, you cannot. The or operator takes only two operands. Additional operands are discarded:

local function f()
    return "a", "b"
end

print(false or f()) --> a
5 Likes

I see, thank you very much.