Page 1 of 1

Probably a very simple case of using functions incorrectly

Posted: Sat Jul 21, 2012 12:58 am
by sanjiv
The following is the essence of my main.lua file. The problem is that the moveObject function doesn't work, even though the exact same code works when not part of a function. Why is this? Am I doing something wrong?

The following code should feature a rectangle that does not move, since it has two equal but opposite sets of instructions acting on it. But right now one set of code works, while the other (the one inside moveObject()) does not.

Code: Select all

function love.load()

	ox,oy=0,0  -- object coordinates

	function moveObject(ox,oy,s,dt)  --should move object diagonally
		ox=ox+s/2*dt	oy=oy+s/2*dt	
	end

end

function love.update(dt)
	
	local s=100 -- set the speed

--because the moveObject function uses negative s, the next two lines of code SHOULD cancel each other out.  Right now that doesn't work.

	moveObject(ox,oy,-s,dt) 
	ox=ox+s/2*dt	oy=oy+s/2*dt

end

function love.draw()
	love.graphics.rectangle('line',ox,oy,10,10)
end


Re: Probably a very simple case of using functions incorrect

Posted: Sat Jul 21, 2012 1:53 am
by Santos
I think this happens because the line:

Code: Select all

ox=ox+s/2*dt   oy=oy+s/2*dt
is changing the values of the local variables ox and oy, and not the global variables. Changing the names of the parameters fixes this:

Code: Select all

function moveObject(ax,ay,s,dt)
    ox=ax+s/2*dt   oy=ay+s/2*dt   
end
Or, you could not pass ox and oy to moveObject.

Code: Select all

function moveObject(s,dt)
    ox=ox+s/2*dt   oy=oy+s/2*dt   
end

moveObject(-s,dt)
I hope this helps! ^^

Re: Probably a very simple case of using functions incorrect

Posted: Sat Jul 21, 2012 7:57 pm
by kalkulatorkredytowy
@Santos Thank you so much for posting this. It fixed similiar issue I had.

Regards