May 152011
 

A simple tutorial teaching you to modularize your code.

For those of you unfamiliar with what this means, it is to spread your code out into different files.

This might not sound like a hugely useful practice, especially if you are still new to Corona and have yet to feel the need for better organization.

Although very basic this tutorial demonstrates some very useful techniques; including simple use of “params”, which is most useful when you need to add multiple identical objects.

The downloadable project file is well commented and as you have likely come to expect by now, the customary “Peach pic” is also present – you can make five of me using the example if you want!

Anyway, this is just a little tutorial I’m hoping will help some of you out – learning to do this was something that I found thrilling and while it’s just par the course now it is still very rewarding to see your code laid out neatly.

As usual, if you have any questions please post them here.

DOWNLOAD THE PROJECT FILE

If you have a request for a template or a tutorial, please vote in the poll (or add your own option) on the Techority Facebook page, which can be found using the widget on the right.

Peach Pellen :)

Like this post? Subscribe to the monthly newsletter!

 

  28 Responses to “How To Modularize Your Code”

  1. How many developers eating from your hand!! Shake your pockets and donate guys! Peach does not eat with compliments.

  2. Hi Peach,

    Thanks for responding to my query.

    My apologies if I have more questions here for you but I’m seem very lost right now.

    I’m really having a hard time understanding the widget, what files are needed to be place in my project folder? I’ve got the button widget working but the tabbar widget is were I’m having problems with. Not so much information in the corona docs (well… at least for me to understand… lol) Is there some resources you can point me to… anything would be really appreciated :)

    I tried getting help at the ansca site (http://developer.anscamobile.com/code/tab-bar) (topnotch374 is my user name) and other developers were really helpful but unfortunately I’m too newbie that I can’t really follow what robmiracle was posting or replying to my query. As mentioned earlier, I’m not sure which files I should be including in my project folder. So far I have the following:

    ui.lua
    director.lua
    config.lua
    main.lua
    theme_ios.lua
    widget_ios folder

    Anyways, I hope you’ll be able to help me… Thanks again Peach!!! :)

  3. Hi Peach,

    First of all, your site is so cool!!! I’m a newbie and i think you have a lot of resources here I can use.

    I’m trying to come up with an App that will have tabs (widget) and using director as well.

    I thought I may ask you, only if you have spare time, to help me with this or maybe you have a template you can email me would be very helpful.

    Basically, I need 4 to 5 tabs on my main screen and from what I’ve read I need to use director for this. I got a working main lua that uses buttons in switching screens but want to use tabs instead.

    Anyways, I hope you have some spare time …lol… regardless… BIG THANKS for all your tutorials here. :)

    • Hey Ron,

      Thanks for the kind words – I do my best :)

      Currently I don’t have a tutorial or template for that kind of thing, however we (Ansca) may have some appropriate sample code; I’m almost certain we do but don’t know what it’s called off hand.

      You should make a post on the Corona forum, in the “The Official Corona UI” sub forum; there you will get answers and, I’m sure, the correct name of the sample code I am thinking of.

      This particular setup doesn’t use Director, although you could do this with Director as well using your own system with buttons. (Which would be fairly simple.) :)

  4. That should be fairly easy to do, you’re right, you’d use a table – or two tables, more likely. One for images and one for text. Or, possibly 4 tables each, it depends.

    As I said before would encourage you to post on the forum; that way you can share the code you have (my comments don’t have syntax highlighting) and I, or others, can better assist :)

  5. Hi, Peach. Thanks for the reply.
    Yes I want to display images,and text strings. I have a images folder for all the images, and I would like to pull 4 different images each time the screen reloads. Maybe I need to use some kind of table.The text is not important right now
    Thanks
    John

  6. Hello Peach, this is my first time to visit the site, and I think from what I’ve read and your help files you would be the person to ask for help. Your site is great!
    I have started an app in which I need to display 4 png’s and 4 text strings. Everytime I open that page 4 different png’s and texts must display. How can I mske this happen? You can tell I’m a real noobe, can’t you.
    Thanks
    John

    • Hey John, thank you for the kind words :)

      You’d be better off asking about this on the forum as it allows for back and forth and you can get email notifications when the thread is updated. (I pretty much live on the Corona forum while awake.)

      Of course am still happy to help you here however I’d need a little more info – are you trying to show random images? I’m not totally sure from your description.

  7. Can you upload your project somewhere please? Troubleshooting via comments is tricky and I’m sure this will turn out to be an easy fix. As I said my above code worked when testing on Mac, Corona .591.

    Peach

  8. correction.

    i tried this to get the background to load but still get the error “Puzzle.lua:15: attempt to index global ‘background’ (a nil value)”

    i need to use director to call background because of all the many scene/levels i have, i would like to generate a random background. so i stripe it down to a barebone main with director and background call.
    still wouldn’t work. ???

    background.lua
    ————————–

    background = display.newImage(“bgBlue.png”)

    Level1.lua
    ———————–
    module(…, package.seeall)

    function new()

    local localGroup = display.newGroup()
    ——————————————————————————
    ——————————————————————————

    local _H = display.contentHeight;
    local _W = display.contentWidth;

    local director = require (“director”)

    require “background”
    local background = background.background
    localGroup:insert(background)

    ——————————————————————————
    ——————————————————————————
    return localGroup
    end

  9. i tried this to get the background to load but still get the error “Puzzle.lua:15: attempt to index global ‘background’ (a nil value)”

    i need to use director to call background because of all the many scene/levels i have, i would like to generate a random background. so i stripe it down to a barebone main with director and background call.
    still wouldn’t work. ???

    background.lua
    ————————–

    bgx = display.newImage(“bgBlue.png”)

    Level1.lua
    ———————–
    module(…, package.seeall)

    function new()

    local localGroup = display.newGroup()
    ——————————————————————————
    ——————————————————————————

    local _H = display.contentHeight;
    local _W = display.contentWidth;

    local director = require (“director”)

    require “background”
    local background = background.background
    localGroup:insert(background)

    ——————————————————————————
    ——————————————————————————
    return localGroup
    end

  10. Setting up modularized code with director isn’t tricky, you just have to approach it from a logical view point.

    The structure is something that perhaps you understand when no additional classes are involved, but in this case, you’ve got it a little bit off – including the director header and footer in your file, which is NOT a scene itself.

    Try this -

    background.lua;

    1
    background = display.newImage("background.png")

    Files in which you want to use background.lua;

    1
    2
    3
    require "background"
    local background = background.background
    localGroup:insert(background)

    Peach :)

  11. this is the error i get calling the first function to background.initBG()

    Puzzle.lua:19: attempt to index global ‘background’ (a nil value)
    ———————–

    Like i said before, i totally understand the structure of modularizing the code. But to put it in work with directors, are there special requirement?

    my background.lua have the director template header and footer. all it does is giving a initBG(), and a randomBG(), which are being call in my main.lua file

    require “background”

    background.initBG()
    randomBG()

  12. Hey Ken,

    Sorry, what error are you getting? I can’t see an error above.

    Peach

  13. Hi Peach,

    Quick question,

    When i try to use your modularize code with director, i get this error when calling the function in the modularize file.

    in my game.lua

    –director header
    ..
    require “background”

    background.initBG
    ..
    –director footer

    I added the require header and footer template in the

    in my background.lua

    – director header
    function initBG()
    .
    .
    .
    end
    –director footer

    what I am trying to do is to use a modular background.lua so I don’t have to type it in each screen.

    Thanks!
    Ken

  14. G$, good stuff. Also nothing I have to write any long response to, so extra good ;) (I’ve had two hours sleep in the past 24 hours and only 5 hours the night before, so I’m getting dopey now. Brain is fried. Sleeping in a minute.) I’m glad you are getting the hang of organizing it all; it’s wonderful, truly :)

    Troy, if you use my saveit.save() command it will save the variable, so save it when leaving “A” and then when you return to “A” you’ll call it and it will be the last recorded one, from leaving A.

    Make sense, or not so much?

    Peach :)

  15. Hey peachy!

    When changing between “modulize” could you show how to “protect” a variable( called “kakapoopoo”) created in, lets say, module “A”. Basically you switch to another module “B” (doing something that does not use kakapoopoo) and then switch back to module “A” and then start using kakapoopoo at it’s last known value upon leaving module “A” the first time.

    Does this sound confusing?

  16. Hi peach, G$ here again to populate your site with colorful commentary, lol yea.

    I think this is something that I am adopting now, which is using modules. After I got the “core” of my game working, I realized that when it gets to like, i dunno 1200 lines of code that things get really, really out of hand and it’s driving me INSANE.

    For example, things like a main.lua which contain all the objects, all the physics properties, all the music (bg music, player death music, main menu music, power up time music…you get the drift), all the tilt controls (I GOT THAT@##@ WORKING PERFECT NOW OH YA GET SOME….ya im happy!), SFX (sound effects)…..then you start getting all the levels and the assets for those it got messy.

    I just started looking at this and here is what I was thinking

    Main.lua has everything like

    platform.lua (which when I get around to utilizing director, I’ll have platform.lua, platform1.lua for each lvl)
    music.lua
    tilt.lua
    sfx.lua
    optionsmenu.lua
    mainmenu.lua

    (the following three, im just making up for now cuz I haven’t gotten this far as looking at HOW to do the below :) hahHaAAHAHaa…not enough time yet! arrrgh)
    openfeint.lua
    facebook.lua
    gamecenter.lua

    I think this might a good way for me to lay things out, i’m really just trying to find a way to create a “template” for myself and future projects so I can spend more time developing instead of trying to mess with all this stuff that isn’t me playing around with my game and making me mad.

    ok, back to coding! I spent a good portion of my day coding, which was really cool. Sorted out alot of issues I was having.

  17. What is the .DS_STORE file in your zip package ? Sorry if its a newbie question.

  18. Thanks Jon,

    I look forward to seeing your example!

    Peach :)

  19. Hi,

    Thanks for the kind words. I am now looking at LUAs interpretation of OOP, not really OOP when compared to JAVA but interesting nonetheless. I will post an example on the Corona code sample page.

    Hey, congratulations on one year with Corona. And happy b’day.

    Jon

  20. I think it’s impressive, being fairly new to a language and picking up on things like that, rewriting, etc is just great :)

    Nicely done.

  21. Hi,

    Not that impressive really, I am just reading up on LUA coding and came across the “seeall()” issue. Also, the fix fits in with my coding style which is to avoid globals and use only locals.

    Jon

  22. Hi Jon (there sure are a lot of “Jon”s around Corona these days!)

    I understand the arguments against using (…, package.seeall) however often when I’m writing my apps I want global variables to be visible/accessible throughout.

    That said, others may not – and I think your code makes a very nice example for those wanting to take that route :)

    Impressive for a Lua noob, indeed!

    Thanks for the kind words and for sharing your work for others to read and learn from as well.

    Peach Pellen :)

  23. Hi,

    I notice that you, and other Corona developers tend to use the LUA module(…, package.seeall). I have read on the LUA forums and a post from Shaunathan on the Corona forum (http://developer.anscamobile.com/forum/2011/03/13/lua-module-function-critiqued) that this is not a recommended approach as package.seeall allows a module to see global variables, which are normally hidden.

    I have rewritten your setup.lua file. The amended version makes the functions local and writes them to a local table which is returned to the calling function – no more globals.

    –[[
    setup.lua rewritten to use locals
    --]]

    – local table to hold references to the functions
    local setupModule = {};

    – Set up the background
    local function background (event)

    – Display the background
    local background = display.newImage (“bg.png”)

    – The function to remove the background
    function killbackground (event)
    background:removeSelf()
    end

    – Add the event listener to the background
    background:addEventListener(“tap”, killbackground)
    end

    – add the local function to the table
    setupModule.background = background;

    – Insert the traditional Peach pic, this time using params
    local function peach (params)

    – My picture
    local peach = display.newImage (“peach.png”)

    – The X and Y of my pic, defined when the function is called
    peach.x = params.x
    peach.y = params.y

    end

    – add the local function to the table
    setupModule.peach = peach;

    – return the table
    return setupModule;

    Your main.lua file only requires a small mod to reference the “setup” file so the local functions
    can be called; change require “setup” to local setup = require “setup”. For example;

    –[[
    Peaches way
    require "setup"
    --]]

    local setup = require “setup”;

    I would be interested in your comments.

    I am a Corona and LUA noob, my background is software development using Java to create business apps, I discovered Corona when looking for a development framework for iOS and I love it. I enjoy reading your site and comments on the Corona forum, you have a fresh easy to follow approach.

    Keep up the great work

    Jon

  24. great stuff peach!
    A world full with peaches would be a better world ;0)

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.