Making HTML5 plugins for Corona

Making HTML5 plugins for Corona

HTML5 opens up some great opportunities for developers and one of those is plugin development using JavaScript.

While most Corona developers will only use Lua in a cross-platform manner like they are currently using, it’s super easy to add JavaScript features to extend your app.

You need two things: a .lua file that tests to see if your platform is HTML5 or some other platform and the actual JavaScript .js file. If you detect you are an HTML5 build, then you require the JavaScript plugin, else provide default functions that prevent those calls from creating errors for the non-HTML5 builds. Consider this code:

If you’re on HTML5, it includes the JavaScript plugin. If not, it simply lets the app know the function isn’t available.

Plugins have to have a unique namespace and that’s accomplished by this line in the .lua file:

Obviously if you intended to publish this to the Corona Marketplace, or if you want to use multiple plugins in your code, the name needs to be unique. Change “myplugin” to a proper name. Then set publisherId to the reverse domain name you use to publish with. For instance, Corona Labs made plugins would have a publisherId of “com.coronalabs“.

Then you create a plugin with the same name except with an _js as part of the name. For instance if your plugin is “awesometimer.lua“, you would create “awesometimer_js.js“. This file will contain your JavaScript code. Here is an example:

We of course can’t teach you JavaScript in this tutorial and there are plenty of examples on the Internet to see. The main point is that you add your plugin to the JavaScript window object, provide your functions as part of the plugin namespace and add your methods to your plugin object.

Then in your .lua modules, i.e. main.lua, you can require the plugin and call the functions as necessary.

This example shows you how to call functions to get data, set data as well as dispatch events from JavaScript back to your Lua code.

You can download the complete sample project from our GitHub repository. If you have questions please reach out on our HTML5 forum!

Rob Miracle
rob@coronalabs.com

Rob is the Developer Relations Manager for Corona Labs. Besides being passionate about helping other developers make great games using Corona, he is also enjoys making games in his spare time. Rob has been coding games since 1979 from personal computers to mainframes. He has over 16 years professional experience in the gaming industry.

No Comments

Sorry, the comment form is closed at this time.