How To: Make your own custom Lunalua library

From PGE Wiki
Jump to navigation Jump to search

In this tutorial you will learn how to make your own custom library. Please note that LunaLua v0.3 is required to use this function. In this example we will do a framecounter. This framecounter will count the frames in the game.

First of all we need to create a new file located in: "{Game Main Path}\LuaScriptsLib\framecounter.lua". Now open your newly created file with your editor of your choice. We want to start with the basic structor of a package:

local myFramecounter = {}

return myFramecounter

All your library-functions will be stored in a table. When API.load (loadAPI and loadSharedAPI for pre 0.7.3) is called, this table will be returned by your library, containing all exposed functions and variables you define. In addition to defining your own variables, you are able to hook into lunalua events from your library.

Now let's do the count function which is counts the frames. In addition we need a variable to store the passed frames:

local myFramecounter = {}
local myCounter = 0 --Our frame counter

--Count the frames
function framecounter.countFrame()
    myCounter = myCounter + 1
end

return myFramecounter

To be able to count the frames we have to hook in the onTick-Event. To do so we have to register the event for our library. The best time to do it is when our libraryis getting loaded. There is an event that lets us do this, called onInitAPI:

local myFramecounter = {}
local myCounter = 0

function myFramecounter.countFrame()
    myCounter = myCounter + 1
end

function myFramecounter.onInitAPI() --This function is called when the user loads our library with API.load.
    registerEvent(myFramecounter, "onTick", "countFrame") --Call countFrame for every loop.
end

return myFramecounter

The last thing we need is a function that is used by the host file. In this example we return the passed frames:

local myFramecounter = {}
local myCounter = 0

function myFramecounter.countFrame()
    myCounter = myCounter + 1
end

function myFramecounter.onInitAPI()
    registerEvent(myFramecounter, "onTick", "countFrame")
end

function myFramecounter.getCurrentFrame()
    return myCounter --Return the passed frames
end

return myFramecounter

We finished our library!

Let's test it with a sample host file:

framecounter = API.load("framecounter")
function onDraw()
    Text.print("Current Frame: "..tostring(framecounter.getCurrentFrame()), 30, 220)
end

Congratulations! You made your first library!