Page 1 of 1

Why are these variables not increasing [SOLVED]

Posted: Sat Nov 03, 2018 8:01 pm
by ITISITHEBKID
From this, I would expect x and z to increase, but for some reason they do not. Why is this?

Re: Why are these variables not increasing

Posted: Sat Nov 03, 2018 8:22 pm
by veethree
Could have just put the code in the post like

Code: Select all

io.stdout:setvbuf("no")	
function love.load()
	x = 42
	z = 42
	y = {x,z}
end

function love.update()
	for i,v in ipairs(y) do
		y[i] = y[i] + 2
	end
	print(x,z)
end
What's happening there is, instead of putting the x and z variables into the y table, You're putting 42 and 42 into it.

Do this instead

Code: Select all

y = {x = 42, z = 42}
and it should work as expected.

Re: Why are these variables not increasing

Posted: Sat Nov 03, 2018 8:26 pm
by ivan
x,z are numbers and you cannot have multiple references to a number variable.
So when you write x=42 z=42 y = {x,z} it's equivalent to writing y = {42,42}
Your code changes y[1] and y[2] but does not change x,z.
Note that the assignment operator "=" works differently with numbers as opposed to tables:
a = 42 b = a means that b = 42
a = {} b = a means that both a and b reference the same table
It's a common mistake, you just get used to it.

Posted: Sat Nov 03, 2018 8:42 pm
by ITISITHEBKID
Thanks for your answers, with your help I fixed the problem