lua-users home
lua-l archive

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


> 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
> one.

In effect, but that is a little imprecise. Numbers don't have "elements"; 
they are atomic wholes. When you say

  m = n

it replaces m's value with the value of n, whatever that was. Eg:

  m = {x = 5, y = 10, z = 20}

  n = "Hello, world"

  m = n

Now m has been well and truly replaced.

n (and m) are now strings, which in Lua are immutable and atomic. For this 
reason, Lua does not let you say:

  n[6] = ":"

You cannot change a "component" of an atomic object. So if vectors were, 
like Python tuples, immutable sequences, you wouldn't be able to say:

  position.x = 10

either. You would have to say something like:

  position = replace(position, "x", 10)

but I have a hunch that you don't actually want to do that.

Would you settle for this?

  position = position ^ {x = 10}

where ^ is read as "replacing"? That would be easy enough to implement:

function meta:__pow(other)
  local rv = {}
  for k, v in self do
    rv[k] = other[k] or v
  end
  return rv
end

or, less efficient but more general:

function meta:__pow(other)
  local rv = {}
  for k, v in self  do rv[k] = v end
  for k, v in other do rv[k] = v end
  return rv
end

Note: if you replace __pow above with __call, you could write it as:

  position = position{x = 10}

Another possibility would be to define an object method, like:

  position = position.with {x = 10}

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

Certainly. You have said that vector and position are the same object. If 
you wanted them to be different objects, you would have had to have said:

  vector = copy(position)

Of course, as we all know, Lua has no copy primitive :)

But clearly the two operations are semantically distinct *for mutable 
objects*.

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

Why not? You don't want to say what you mean? :) What if you *meant* for 
them to be the same object?

R.