separating files causes unexpected nil values
Posted: Wed Mar 18, 2015 1:20 am
In an effort to clean up some of the code I've been writing recently in Löve, I separated my game into a couple of files. Unfortunately, I'm finding that my enemies now have their sprite_index field come up as nil, even though they're being very explicitly set. My code looks like this:
Main.lua:
Sprites.lua:
Enemies.lua:
when I go to draw the enemies using the following code in main:
I'm told that sprite_index is a nil value. Can anybody identify a problem in my code that might be causing this? I'm still very new to Lua and Love, so please give as many details as you can.
Thanks in Advance,
Nicholas
Main.lua:
Code: Select all
require "math"
require "sprites"
require "player"
require "enemies"
math.randomseed(os.time())
function love.load()
--images--
love.graphics.setBackgroundColor(255,255,255)
loadImages()
--enemies--
enemies = {}
for i = 0,4 do
table.insert(enemies,Enemy:new())
end
end
Code: Select all
function loadImages()
spr_slice = love.graphics.newImage("slice.png")
spr_agent = {}
spr_agent[1] = love.graphics.newImage("agentf1.png")
spr_agent[2] = love.graphics.newImage("agentf2.png")
spr_player = {}
spr_player[1] = love.graphics.newImage("playerf1.png")
spr_player[2] = love.graphics.newImage("playerf2.png")
end
Code: Select all
Enemy = {}
Enemy.sprite_index = spr_agent
Enemy.image_timer = 0
Enemy.image_index = 1
Enemy.image_speed = 3
Enemy.x = 0
Enemy.y = 0
Enemy.direction = math.random()*360
Enemy.speed = 2*60
Enemy.__index = Enemy
function Enemy:new(o)
local o = o or {}
setmetatable(o, Enemy)
self.__index = self
o.x = math.random()*love.graphics.getWidth()
o.y = math.random()*love.graphics.getHeight()
o.direction = math.random()*360
return o
end
Code: Select all
for i,v in ipairs(enemies) do
love.graphics.draw(v.sprite_index[v.image_index],math.floor(v.x),math.floor(v.y),0,sign(lengthdir_x(1,v.direction)),1,spr_agent[1]:getWidth()/2,spr_agent[1]:getHeight()/2)
end
Thanks in Advance,
Nicholas