Hi Sarvi,
On Wed, Jan 8, 2014 at 1:01 AM, Sarvi Shanmugham <
sarv...@gmail.com> wrote:
> 2. Should the following work, swapping the values?
> tok1.pos,tok2.pos = tok2.pos,tok1.pos
You're falling into the same trap as someone recently did on the
LuaJIT mailing list about LuaJIT's FFI. No, this cannot work.
The issue is that reading "tok1.pos" does not create a copy of the
structure tok1.pos --- you don't want a copy, because otherwise
"tok1.pos.foo = 5" would change the value of the "foo" field in the
copy, which would then immediately be thrown away. So "tok1.pos"
returns a structure that is a *reference* to the substructure inside
"tok1". And the copying operation occurs only when executing
"tok2.pos = ...", which takes (in this case) the reference to the
substructure, and copies it into "tok2.pos". There is basically no
other way in Python.
Combine this explanation with the "tok1.pos,tok2.pos =
tok2.pos,tok1.pos" case and you'll understand why it doesn't work as
you would expect. It is the same reason for why, if "lst1" and "lst2"
are lists, then "lst1[:], lst2[:] = lst2, lst1" fails to swap the
content of the lists.
Like in C, you need three copies: p=ffi.new("struct position *");
p[0]=tok1.pos; tok1.pos=tok2.pos;tok2.pos=p[0]
A bientôt,
Armin.