lua-users home
lua-l archive

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


2015-07-08 19:52 GMT+02:00 Andrew Starks <andrew.starks@trms.com>:

> I don't think I saw this earlier, but given the following:
>
> function Tuple(...)
>   local co = coroutine.wrap(function (...) while true do
> coroutine.yield(...) end end )
>   return co, co(...)
> end
>
> t = Tuple("foo", 5)

This sort of Tuple is not what I intended this time round, though
with enough ingenuity it could fit in. This kind means "a contiguous
block of values on the runtime stack, created via a vararg or a multiple
return and accessible as a vararg."

I mean by 'tuple' an array stored as a table, with only an array part,
and not allowing "rawset". An immutable table.

> And so a Tuple might be any object that produces a new object if it is
> modified?

That's usually called "copy-on-write semantics".

> (or errors?)

Yes.

> The benefit being an object that behaves like a basic type, when it
> comes to equality?

If you mean "compare-by-value", yes.

> Lua strings are tuples, correct?

Yes.

> I should use them In places where I would otherwise need to do deep
> inspection, etc.?

That's too idiosyncratic.

You should use them when you don't want any later code to change
the values.

> In other languages, tuples may hint a compiler or otherwise provide
> efficiency benefits?

In C, it's merely a protection, but optimizing compilers would be able
to exploit them.

In Python, they are just immutable arrays.

> If the above is correct, I may only be missing the ability to recognize when
> I should reach for them.

Assuming (...) rather than {} to denote tuples:

days_of_the_week =
("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
defaults = (...)
options = ml.import({},defaults) -- options is mutable

x[(1,2,3)] = 1.234
y = x[(1,2,3)]  -- (1,2,3) is interned like a string, so this works
-- x[{1,2,3}] does not work, a new table is generated for every {1,2,3}