Page 1 of 1

can't figure out why i'm getting a nil error

Posted: Thu Mar 28, 2013 3:59 am
by Semaphore
Hey guys, for some reason I'm getting a nil error when attempting to draw the player, cannot figure out for the life of me why.

Code: Select all

player = {}

function player.load()
	player.body = love.physics.newBody(world, 650/2, 650/2, "dynamic")
	player.shape = love.physics.newCircleShape(20) --radius of 20
	player.fixture = love.physics.newFixture(player.body, player.shape, 1) --density of 1
	player.fixture:setRestitution(0.2) --ball bounces slightly
end

function player.draw()
	love.graphics.setColor(255, 0, 0)
	love.graphics.circle("fill", player.body:getX(), player.body:getY(), player.shape:getRadius())
end
Gives me the following error:

Code: Select all

Error

player.lua:12: attempt to index field 'body' (a nil value)

Traceback

player.lua:12: in function 'draw'
main.lua:19: in function 'draw'
[C]: in function 'xpcall'
However, when I draw the player in my objects file, it works fine:

Code: Select all

objects = {}

function objects.load()
	objects.ground = {}
	objects.ground.body = love.physics.newBody(world, 650/2, 650-50/2)
	objects.ground.shape = love.physics.newRectangleShape(650, 50) --width 650, height 50
	objects.ground.fixture = love.physics.newFixture(objects.ground.body, objects.ground.shape)
	
	objects.player = {}
	objects.player.body = love.physics.newBody(world, 650/2, 650/2, "dynamic")
	objects.player.shape = love.physics.newCircleShape(20) --radius of 20
	objects.player.fixture = love.physics.newFixture(objects.player.body, objects.player.shape, 1) --density of 1
	objects.player.fixture:setRestitution(0.2) --ball bounces slightly
end

function objects.draw()
	--draw the ground
	love.graphics.setColor(0,0,0)
	love.graphics.polygon("fill", objects.ground.body:getWorldPoints(objects.ground.shape:getPoints()))
	
	--draw the player
	love.graphics.setColor(255, 0, 0)
	love.graphics.circle("fill", objects.player.body:getX(), objects.player.body:getY(), objects.player.shape:getRadius())
end
Really stumped on this one. Any suggestions? I'll attach a .love of the whole thing too (with the player commented out of objects.lua)

Re: can't figure out why i'm getting a nil error

Posted: Thu Mar 28, 2013 4:05 am
by Boolsheet
You put the player initialization stuff into the player.load function, but you never call it. You probably want to call it in love.load.

Re: can't figure out why i'm getting a nil error

Posted: Thu Mar 28, 2013 4:50 pm
by Semaphore
Well, I feel dumb now, that did it. Thanks. :?