Montag, 24. Dezember 2012

Corona SDK lua tutorial: Callback functions

Hey guys,

during development we've realized that so called callback function are a very usefull system to create reusable code that makes life easier. We've used that system in our slide-View that we've implemented as our game selection menu in Cookie Billiard  Android app on Google Play .

The idea and purpose of callback functions:

A callback function atually is nearly the same as an EventListener. You specifiy which method should be called in case a certain event occures. In the context of the slide view a certain method should be called if a user clicks on a specific slide. In order to make it reusable the method is not allowed to be located within the slide view module, but outside of it. You pass a certain function into the slide view module.

Have a look at the new function of our slidev view module:

function slideView:new( svTop, svLeft, images, keys, callback )

Here we pass the distance to the top, to the left, all images, their keys and a function that should be called whenever a slide was clicked (tapped in corona terms).

To use the passed callback function you can use the following listener:

function onImageTap( touchEvent )
        callback( { key = } )
        return true

Our callback function than looks like this:

This function is not part of the slide view module but resides outside!

local function onSelectSlideViewItem( slideViewItem )
        print( "Clicked " .. slideViewItem.key )

        if (slideViewItem.key == "minigames") then
            director:changeScene( "", "moveFromTop" )
        elseif (slideViewItem.key == "gameCrispy") then
            director:changeScene( "scripts.levels.crispy.levelSelectionCrispy", "moveFromTop" )
        elseif (slideViewItem.key == "introduction") then
            director:changeScene( "scripts.levels.introduction.introduction", "moveFromTop" )
        elseif (slideViewItem.key == "gameCrunchy") then
            director:changeScene( "scripts.levels.crunchy.levelSelectionCrunchy", "moveFromTop" )

The callback function receives a certain item that was clicked and can decide upon that what action has to follow.

Our System of a slideview makes it perfectly reusable. W can use it for any other game. We just have to pass all the required parameters and thats it for the slideview.

Android app on Google Play

Keine Kommentare:

Kommentar veröffentlichen