Game Code

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
Omishie
Prole
Posts: 1
Joined: Mon Jun 08, 2020 6:31 am

Game Code

Post by Omishie »

So i'm trying to make a game and i'm pretty sure i defined player but this error still shows up
Error

main.lua:16: attempt to index global 'player' (a nil value)


Traceback

main.lua:16: in main chunk
[C]: in function 'require'
[C]: in function 'xpcall'
[C]: in function 'xpcall'
here's my code:

function love.load()
player = {}
player.x = 0
player.y = 550
player.bullets = {}
player.fire = function()
bullet = {}
bullet.x = player.x + 35
bullet.y = 400
player.cooldown = 20
player.speed = 10

end
end

if player.cooldown <= 0 then
player.cooldown = 20
end

enemies_controller = {}
enemies_controller.enemies = {}

function enemies_controller:spawnEnemy()
enemy = {}
enemy.x = 0
enemy.y = 0
enemy.bullets = {}
enemy.cooldown = 20
enemy.speed = 10
table.insert(self.enemies, enemy)
end

function enemy:fire()
if self.cooldown <= 0 then
self.cooldown = 20
bullet = {}
bullet.x = player.x + 35
bullet.y = player.y
table.insert(player.bullets, bullet)
end
end
function love.update(dt)
if love.keyboard.isDown (Left) then
player.x = player.x - 5
elseif love.keyboard.isDown (Right) then
player.x = player.x - 5
elseif love.keyboard.isDown (Up) then
player.y = player.y + 5
elseif love.keyboard.isDown (Down) then
player.x = player.x + 5
end
end

function love.draw()
--drawing the player
love.graphics.rectangle("fill", player.x, 10, 100, 100)
love.graphics.setColor(100, 0, 0)
for _,v in pairs(player.bullets) do
love.graphics.rectangle("fill", v.x, v.y, 10, 10)
end
end
Xugro
Party member
Posts: 112
Joined: Wed Sep 29, 2010 8:14 pm

Re: Game Code

Post by Xugro »

The problem is that your code will be loaded and executed first and after that love.load() will be called. This means that player in line 15 is not defined yet. Put that piece of code inside love.update().
User avatar
zorg
Party member
Posts: 3446
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Game Code

Post by zorg »

Do use code tags since that makes code actually readable.
Also, you need to put the player variable into the file scope, NOT into love.update, since you want to access it from both places.

Code: Select all

local player
outside any functions at the top will do.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
Post Reply

Who is online

Users browsing this forum: No registered users and 8 guests