That facepalm moment when ...

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
milon
Party member
Posts: 472
Joined: Thu Jan 18, 2018 9:14 pm

Re: That facepalm moment when ...

Post 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
Any code samples/ideas by me should be considered Public Domain (no attribution needed) license unless otherwise stated.
ZuccaroMateo
Prole
Posts: 17
Joined: Tue Jul 14, 2020 11:07 pm

Re: That facepalm moment when ...

Post 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?
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 5 guests