is it closure?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

is it closure?

Dinesh Gandhewar
function test(y)
  local t = {} --here t is local to funcion test
  y.my = t
end 

x = {}
test(x) --here whether x.my is still valid?

Kindly note -- line.
Thanking you,


Reply | Threaded
Open this post in threaded view
|

Re: is it closure?

Philippe Verdy
t is a local reference (within test()) to the empty array. That reference is assigned to the "my" property of the parameter y. The array then has two references.
When the function test() returns, the local reference is dropped, but the parameter y (whose value is a copy of x which is also a reference) still contains the empty array that was assigned to t.
So yes, x.my will be valid after test() returns, so you get x == {my: {}}.


Le lun. 18 mars 2019 à 05:08, Dinesh Gandhewar <[hidden email]> a écrit :
function test(y)
  local t = {} --here t is local to funcion test
  y.my = t
end 

x = {}
test(x) --here whether x.my is still valid?

Kindly note -- line.
Thanking you,


Reply | Threaded
Open this post in threaded view
|

Re: is it closure?

Tim Hill
In reply to this post by Dinesh Gandhewar

> On Mar 17, 2019, at 9:00 PM, Dinesh Gandhewar <[hidden email]> wrote:
>
> function test(y)
>   local t = {} --here t is local to funcion test
>   y.my = t
> end
>
> x = {}
> test(x) --here whether x.my is still valid?
>

This isn’t a closure issue .. it’s just that tables are passed by reference. So your test() function is modifying the table in the global “x”, and so yes, after the call there will be a table in x.my that contains a table. This is nothing to do with capturing the “t” variable in test(), its just that the reference to the table in t is COPIED to y.my (when y references the same table as x).

—Tim