Why are these variables not increasing [SOLVED]

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
ITISITHEBKID
Prole
Posts: 18
Joined: Tue Apr 24, 2018 7:37 pm

Why are these variables not increasing [SOLVED]

Post by ITISITHEBKID »

From this, I would expect x and z to increase, but for some reason they do not. Why is this?
Attachments
main.lua
(176 Bytes) Downloaded 112 times
luaproj.love
(246 Bytes) Downloaded 105 times
Last edited by ITISITHEBKID on Sat Nov 03, 2018 9:21 pm, edited 1 time in total.
User avatar
veethree
Inner party member
Posts: 877
Joined: Sat Dec 10, 2011 7:18 pm

Re: Why are these variables not increasing

Post 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.
User avatar
ivan
Party member
Posts: 1918
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Why are these variables not increasing

Post 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.
ITISITHEBKID
Prole
Posts: 18
Joined: Tue Apr 24, 2018 7:37 pm

Post by ITISITHEBKID »

Thanks for your answers, with your help I fixed the problem
Post Reply

Who is online

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