Page 1 of 1

separating files causes unexpected nil values

Posted: Wed Mar 18, 2015 1:20 am
by LastNameGames
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:

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
Sprites.lua:

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
Enemies.lua:

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
when I go to draw the enemies using the following code in main:

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
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

Re: separating files causes unexpected nil values

Posted: Wed Mar 18, 2015 1:42 am
by Evine
You set the variables in the wrong order.

Code: Select all

Enemy.sprite_index = spr_agent -- Here spr_agent is = nil
spr_agent = {} -- Now spr_agent becomes an table
               -- Enemy.sprite_index is still = nil
Be aware that the love.load() function is called after the variables outside functions is set.

Code: Select all

function love.load()
    a = 5
end
b = a -- This is calculated/run before the function love.load() is run.
      -- Which leads to b = nil

Re: separating files causes unexpected nil values

Posted: Wed Mar 18, 2015 1:46 am
by LastNameGames
Wow. I'm a little bit embarrassed that I missed that. Thanks very much for clearing up the confusion. It actually makes perfect sense, now.