Starlight enables you to run Lua scripts in a webpage by placing Lua code in
Here’s a simple example:
As you can see we wrap the Lua code in a
<script> tag with
We’re also including the Babel browser runtime because Starlight outputs ES6 and, for the time being at least, most browsers do not fully support ES6. Hopefully over time the need to include Babel will reduce significantly. See also Using Starlight with Grunt to discover how to precompile your scripts and negate the need for Babel.
You’ll also need to include Starlight itself. We’re using the boolean attribute
data-run-script-tags here to tell Starlight to execute the scripts on page load. Without this attribute the scripts will need to be executed manually.
That’s all you need to get started. Notice that the
print() function will output to the browser’s console window. This can be modified in the Starlight configuration.
Starlight will parse any
<script> tags with the following
Including remote scripts
src attribute. One difference, however, is that files are loaded over
Scripts are loaded and parsed in the order that they appear in the page. You can add a
defer attribute to defer the loading of the script until after others have loaded, so that your script does not block. The
defer attribute is ignored on inline script tags.
A nice way to use the parser in this manner is to place the Lua code in script tags and execute these on demand. In this case, remember to prevent your Lua scripts from executing on page load, by not adding the
You can also turn your script tag into a Lua module by giving it a
data-modname attribute. This script will be preloaded but not executed and can later be required by any other Lua script. Make sure you define a module in a tag that precedes those that require it, in the order they appear in the page.
data-modname attribute can also be used on remote script tags. When using script tags, all modules need to be explicitly defined within the page; using
fibonacci-module.lua /fibonacci-app.lua JS Bin on jsbin.com
The configuration object is
window.starlight.config and can currently be used to override the destination of
stdout and add variables to the Lua global namespace.
In the following example, we are redirecting the
stdout to output to a DOM element instead of the browser’s console window.