With the info given, it's all guesswork, but the error message is telling a certain story.
The error happens inside `bullet.lua`, not inside `main.lua`, and it happens inside `love.draw()`. Specifically in line 21, when trying to take the length of a global variable called `bullets`, it's not initialized. This may seem surprising given that it's defined in `love.load()` in the same file.
My guess is that you have several `love.load()` events in different files, but that won't work. Only the last executed definition will prevail, and given that `bullets` is not defined, it seems to me that the one that prevails is not the one inside `bullet.lua`, yet the `love.draw()` that prevails is. That's why the error happens in `love.draw()` inside `bullet.lua` and why `bullets` is not defined.
You need a bit more organization. Place all the events in `main.lua`, and call each file's initialization, update and draw functions from them. There are several ways to do this, but a common approach is to have each file define a table with functions specific to the object it's dealing with, and then have `main.lua` call them from the appropriate event.
For example, instead of having `love.load()` and `love.draw()` inside `bullet.lua` (which is incorrect for the reasons mentioned earlier), you have them inside `main.lua` only. The file `bullet.lua` would declare a table which could be called Bullet, with upper-case B, where all bullet-related functions would go, for example taking your code:
Code: Select all
Bullet = {}
function Bullet.load()
bullets = {}
Bullet.sprite = love.graphics.newImage('sprites/bullet.png')
end
function Bullet.update(dt)
end
function Bullet.keypressed(uselesskey, key)
if key == 'space' then
table.insert(bullets, {
x = player.x,
y = player.y,
})
end
end
function Bullet.draw()
love.graphics.print("text", 200, 200)
for bulletIndex, bullet in ipairs(bullets) do
love.graphics.setColor(0, 1, 0)
love.graphics.circle('fill', bullet.x, bullet.y, 5)
end
end
I've also fixed a couple things. Note that I've put the sprite inside `Bullet`. I've also removed the `if #bullets > 0` check because the loop will be executed zero times just fine when it's empty.
Finally, you've given no information about the rest of files in your project, but here's how your `main.lua` could look like, in the part that refers to bullets:
Code: Select all
require('bullet')
function love.load()
Bullet.load()
end
function love.keypressed(...)
Bullet.keypressed(...)
end
function love.update(dt)
Bullet.update(dt)
end
function love.draw()
Bullet.draw()
end
In each event, you would add calls to every other type of object you have (Player, Enemy, ...) as needed.