[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Arguments by reference?
- From: Ben Sunshine-Hill <sneftel@...>
- Date: Thu, 1 Sep 2005 11:09:48 -0700
On 9/1/05, Brent Arias <barias@signaturedevices.com> wrote:
> Wow! Now this is bewildering:
>
> ------------------
> They might look like they're being passed by reference, but they're
> not. All arguments in Lua are passed by value. They are not passed by
> copy, so when you pass a table (by value) you are passed the same
> table,
> ------------------
Alright. Here's what's going on. When you have a table in a variable,
that variable doesn't actually contain the table. It contains a
REFERENCE to the table. On the VM level, this is actually a pointer.
The semantics for a table reference, actually, are pretty much the
same as those of a C pointer (without pointer arithmetic, of course).
The REFERENCE is copied, but the TABLE itself is not copied. Here's an
example.
t = {a = 1} -- t holds a reference to a new table, and the table holds
a single k/v pair
r = t -- r and t now hold references to the SAME table
r.a = 2 -- the table referenced by both r and t is modified
r = {b = 4} -- r now points to a new table
function foo(tbl) tbl.a = 4 end
foo(t) -- the function foo receives a reference to the table which t
references, and modifies that table
The acid test of whether a language is pass-by-reference or
pass-by-value, BTW, is whether it can swap with a function such as
this:
function swap(a, b) local tmp = a; a = b; b = tmp; end
In Lua, you will find that the values a and b in the function which
calls swap() will still point to the same tables afterwards. (Very few
modern languages are pass-by-reference.)
Ben