How To: Make your own custom Lunalua library
In this tutorial you will learn how to make your own custom API. 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 api-functions will be stored in a table. When API.load (loadAPI and loadSharedAPI for pre 0.7.3) is called the api file will return the api-table and stores it. Now you have the ability to hook in events.
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 onLoop-Event. To do so we have to register the event for our api. The best time to do it is when our API is getting loaded (by 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 API with loadAPI.
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 API!
Let's test it with a sample host file:
framecounterAPI = API.load("framecounter")
function onDraw()
Text.print("Current Frame: "..tostring(framecounterAPI.getCurrentFrame()), 30, 220)
end
Congratulations! You made your first API!