Page 2 of 2

Re: That facepalm moment when ...

Posted: Thu Mar 04, 2021 1:57 pm
by milon
This is the correct answer:
MrFariator wrote: Wed Mar 03, 2021 6:19 pm
ZuccaroMateo wrote: Wed Mar 03, 2021 3:56 pm hey, why is it printing 1 1?
Tables are passed by reference in lua. As such, if you pass in a table and do some modifications on it, then those changes will persist even after the function finishes. However, in the posted code, when the reset_vector is any non-falsey value, the table the variable "vector" points to doesn't get modified. Instead, the "vector" variable is reassigned to look at a new table. This leaves the original table untouched, so the code will print 1,1 after the function is over.

The correct code for the function would be like

Code: Select all

function update_vector (vector, reset_vector)
  if reset_vector then 
    vector[1] = 0
    vector[2] = 0
  end
end

Re: That facepalm moment when ...

Posted: Thu Mar 04, 2021 2:22 pm
by ZuccaroMateo
MrFariator wrote: Wed Mar 03, 2021 6:19 pm Tables are passed by reference in lua. As such, if you pass in a table and do some modifications on it, then those changes will persist even after the function finishes. However, in the posted code, when the reset_vector is any non-falsey value, the table the variable "vector" points to doesn't get modified. Instead, the "vector" variable is reassigned to look at a new table. This leaves the original table untouched, so the code will print 1,1 after the function is over.

The correct code for the function would be like

Code: Select all

function update_vector (vector, reset_vector)
  if reset_vector then 
    vector[1] = 0
    vector[2] = 0
  end
end
That's deeper than I knew before. You teach me something! Thank you. I really appreciatte this community. How can I colaborate to LÔVE?