Director Class and Modules / external files

Finally figured out loading external modules into a main file with director class and still be able to switch scenes and have nothing break!!

OK, not sure which forum this should be best posted in because I was originally trying to get Director class working with Sprite Deck which successfully loads an external file for its images into the main file.

Anyway the problem I had was I had my main game screen, a game level screen and a main menu button back to the menu screen which if I left things alone with what outputted from Sprite Deck and put all my code into the Level.lua file then everything would work ok.

But... my controls code was a bit lengthy and I waned to move it into another Controls.lua file and make it a bit more dynamic so if I chose to have 50 levels I wouldn't have to re-write all those control functions.

Originally when I tried several work arounds I could get one or the other to work, either my controls or the menu button but never both.

Heres my solution which consistently works and if I'm not mistaken I have been told and read this a few times but it never sunk in.

The Solution:

Ok I've been working with Sprite Deck and if you have as well then your aware of the two files it outputs for each screen for this I'll be using Level.lua and _Level.lua and my own created external module containing just one function called Test.lua.

Leave _Level.lua alone it contains the "this" display group (or localGroup for Director fans) but it doesn't matter, also for updates out of Sprite Deck you'll want to leave this alone.

Set up your Test.lua file as follows:

-- test.lua
module(..., package.seeall)
function test () -- Your function
  local this = display.newGroup() -- the name of the group you put all your object in
  local chris = display.newText("chris is amazing",50, 50, Helvetica, 30) -- this is the contents of your function, could have been anything.
  this:insert(chris) -- Remember to insert your objects into the same display group as Sprite Deck which is 'this' or localGroup if your not. If what your doing isn't a display object then don't bother inserting it.
  this.chris = chris
 return this -- remember to return 'this' or localGroup

Thanks for your help buddy, this really helped me understand how to create modules and use the director class to clean up scenes.

views:956 update:2011/10/12 18:33:00
corona forums © 2003-2011