Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Using an If statement with Tuples?

Here's an example I pulled from another submitted question.

function gets()
    return 7, 17
end

apple, banana= gets()
print(apple) -- 7
print(banana) -- 17

My question is, how do you use an if statement when returning two values? Here, I'll show you what I mean.

function gets()
    return 7, 17
end

print(gets()) -- 7, 17
if gets() ==  7 then print("7") --7
if gets() == 17 then print("17") --nothing

Is there a way to use both returned values in an if statement? Thanks!

2 answers

✓ Accepted answer

You still need to store the values returned somewhere. You can do this in two ways:

Example 1:

local function tuple()
	return 1, 2, 3
end

local a, b, c = tuple()
-- Do what you want with a, b, and c
-- Example:
if a == 1 and b == 2 and c == 3 then
	-- do stuff
end

Example 2:

local function tuple()
	return 1, 2, 3
end

local values = {tuple()}
-- Access each value by indexing the table
-- Example:
if values[1] == 1 and values[2] == 2 and values[3] == 3 then
	-- do stuff
end

Not directly.

With three exceptions, all operations throw away all except the first value of a tuple. This includes, for example, ==.

e.g., if you define pair() as

function pair()
	return 1, 2
end

function triple()
	return 1, 2, 3
end

all of the follow are equivalent:

  • pair() + 5 is just 1 + 5
  • x = pair() is just x = 1
  • pair() == 3 is just 1 == 3
  • (pair()) is just (1) -- this is definitely an interesting one
  • a, b = pair(), 5 is just a, b = pair()
  • list[pair()] is just list[1]

The three cases that actually treat tuples as tuples are assignments, table literals, and function calls. All three, the tuple only survives if it's the final thing in its sequence:

a, b, c, d = 4, triple() -- a = 4; b = 1; c = 2; d = 3;
a, b, c, d = triple(), 4 -- a = 1, b = 4, c = nil

list = {5, triple()} --> {5, 1, 2, 3}
list = {triple(), 5} --> {1, 5}

print(5, triple()) --> 5 1 2 3
print(triple(), 5) --> 1 5

Using tuples

You can write a function to use tuples, of course!

function anyEqual(value, ...)
	for i = 1, select("#", ...) do
		if select(i, ...) == value then
			return true
		end
	end
	-- here's another implementation:
	for _, element in pairs{...} do
		if value == element then
			return true
		end
	end
end

if anyEqual(7, gets()) then
	-- true!
end

Though this really isn't the most readable or reasonable solution to this.

If the values are truly 'packaged together' in some way that it's tempting to write code that looks like this, it probably means they should actually be a single object (values stored together in a table or list or dictionary)

This discussion is preserved as it was. New answers, comments, and votes are closed.