lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> On Jul 8, 2015, at 10:52 AM, Andrew Starks <> wrote:
> This is one of those invaluable bonus threads. I've heard OF tuples but I didn't know what they were and I still don't comprehend their apparent significance. If anyone (on or off list) would like to point me to their favorite "Why Should I care about Tuples" document, please do. I've been googling it with "okay" results. 

One way to look at tuples is as an extension of the multiple return value paradigm in Lua into a general way of treating a set of values as a single aggregate value. In this sense tuples are a collection type, but they are typically designed to be very lightweight and cheap, both in syntax and in implementation overhead.

For example, in Lua you can do something like:

a, b, c = 10, 20, 30

You can also do this in Python:

a, b, c = 10, 20, 30

However, in Python what you are really doing is something like this:

x = 10, 20, 30
a, b, c = x

That is, the syntax ’10, 20, 30’ in Python is a value, whose type is a tuple. Since it’s a value, it can be saved in a variable (as above), passed as a (single) argument, or returned from a function. Thus, in Python, you don’t really have functions that can return multiple values, you have functions that can return one value that might be a tuple:

def somefunc():
	return 10, 20, 30

x = somefunc()
a, b, c = x

Typically tuples are immutable, which is done for several reasons. First, as per this thread, they can be used where a value that can change is problematic, such as the key of a dictionary or associative array. Also, immutable values in compiled languages allow the compiler to perform some significant optimizations.

The cheapness is also significant, especially for script languages. Consider a simple (x,y) point. In C++ you might create a class to contain such a value, which entails some coding overhead (copy constructors etc etc). With a tuple you just pair together two numeric values (10,20) and you are done. Yes, you don’t get type safety, but in some cases (especially small scripts) that really isn't that important.