lua-users home
lua-l archive

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

Brent Arias wrote:

> Ok, so provided the object isn't const, then the summary
> (in my lingo) is:
> lua passes primitives by value, and ADTs by reference.
> I presume you'll tell me I'm mistaken, but man I gotta
> tell you, the explanation of why passing by reference in
> lua, is not passing by reference - is altogether too
> esoteric for me.  :)

In the following example, nothing Fun does with Param can
change the value of Var.

  function Fun(Param)
    -- ...
  end -- Fun


If Var is a string and Fun does

    Param = 42

then Var will still be the same string after Fun returns.
If Var is a table and Fun does

    Param = {"New table"}

then Var will still be the same table (not the new one that
Fun created) after Fun returns.  The only way Fun has of
making changes that its caller will see, a la the type of
thing that some languages use pass-by-reference for, is what
the Lua Reference Manual calls an indexing assignment:

    Param[1] = "Hello to caller"


    Param.Msg = "Hello again"

Neither of those lines reassign another value to Var; they
only *mutate* the value that's already in Var.  (And they'll
cause an error if Var doesn't contain a table or something
tricked out to look like a table via a metatable.)

It may seem as though people are making a big deal out of a
subtle terminological quibble, but I'd like to add something
from personal experience that may explain this.

When I first learned Lua, I had the rule of thumb in my head
that Lua passes by value, except for tables, which are
passed by reference.  This caused me to think incorrectly
about my code.  It was something of an enlightenment
experience to understand what was really going on, and since
then I have seen this erroneous belief cause other people to
write code that doesn't work.  I wouldn't be surprised if
other people on the list have had similar experiences.