Page 1 of 1

Game Code

Posted: Mon Jun 15, 2020 3:21 am
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

Re: Game Code

Posted: Mon Jun 15, 2020 9:58 pm
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().

Re: Game Code

Posted: Tue Jun 16, 2020 6:36 am
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.