lua-users home
lua-l archive

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

Dylan Cuthbert wrote:
The problem is that tables are passed by reference, meaning I get a lot of
variables all "pointing" to the same value, which I then access by element
(x,y,z, or w) affecting all those variables.  This doesn't happen with ints
or floats, because when you modify the value it *replaces* it with the new


position = { x=5, y=10, z=20 }
vector = position
position.x = 10        -- vector also "changes"!!   arghhh

and no.. writing vector = vector.copy( position) or some such is *not* an
option. ;-)

I feel your pain.  It's not so bad; in my own vector class
(using a home-grown object system in lua) I have to do
vectorb = vectora:copy() quite a lot though... and if I
forget, all hell can /silently/ breaks lose. :)

I often wish that there were a 'copy' metamethod so that
a table on the RHS of an assignment can return a reference
to a copy instead of a reference to itself in these instances.

It just occurred to me that a syntax that might be nice would
be something like vectora = *vectorb -- it's a bit C-like.  But
then I thought that the same thing could (unintuitively) be
achieved right now by overloading the unary-minus metamethod:

vectora = -vectorb    -- take a copy

But of course, this is seven flavours of wrongness-looking,
especially for a vector class!  (-vec already has a meaning.)

If Lua treated the expression '-tab' as __sub(nil,tab)
then unary-minus could disappear, as the user's __sub
metamethod could detect and handle it as a special case (and e.g.
if '*tab' was a valid expression in Lua's syntax, the same
thing could apply for the other binary operations, allowing,
say, the now-pseudo-unary multiply to return a reference to
a copy of the table).

Adam D. Moss   . ,,^^   co:3
"When I was young, I would break down and cry whenever mom made me
throw an empty toilet paper tube in the trash can. I just imagined
it sitting at the dump, all cardboard and sad." -- T.Farnon