Probably a very simple case of using functions incorrectly

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
User avatar
sanjiv
Citizen
Posts: 88
Joined: Mon Feb 27, 2012 5:11 am

Probably a very simple case of using functions incorrectly

Post 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

Santos
Party member
Posts: 384
Joined: Sat Oct 22, 2011 7:37 am

Re: Probably a very simple case of using functions incorrect

Post 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! ^^
kalkulatorkredytowy
Prole
Posts: 1
Joined: Sat Jul 21, 2012 7:55 pm

Re: Probably a very simple case of using functions incorrect

Post by kalkulatorkredytowy »

@Santos Thank you so much for posting this. It fixed similiar issue I had.

Regards
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 3 guests