lua-users home
lua-l archive

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


Brent Arias 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,
------------------

Not passed by reference? And not passed by copy either?  I don't get it.
Those are the only two options.  If its not a reference/pointer, and its not
a copy of the value...then...what?

Perhaps this is just a semantics issue.  Perhaps a variable "containing" a
table, internally is implemented somewhat like a pointer, but is exposed to
lua as a regular variable.  If that is the case (and I suppose that is
correct), then you could say tables are passed by value, yet modifying the
content of the passed table will indeed affect the original (as if it were a
pass by reference).

Lua behaves like most other scripting languages, like Javascript and Python. Every data type is passed by value. But the value of an "object" (tables and userdata in Lua) is a reference to that object. So you can go:

    function foo(bar) bar = 5 end

and you have just changed the value of the passed parameter, obliterating what it was before. There is no way to get this to change the value passed in. For instance, in C++ you can do something like:

    void foo(int& bar) { bar = r; }

and the value of the value passed in will be changed. To do something similar in Lua or any scripting language in this class, you would have to encapsulate your value into a table like this:

    function foo(bar) bar.value = 5 end

    local a = { }
    foo(a)
    print("a is ",a.value)

Hope that helps...

--
chris marrin                ,""$,
chris@marrin.com          b`    $                             ,,.
                        mP     b'                            , 1$'
        ,.`           ,b`    ,`                              :$$'
     ,|`             mP    ,`                                       ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`
"As a general rule,don't solve puzzles that open portals to Hell"'