How do I call a Lua script from an HTML5 script/file/page

On the client-side, you can use:

  • Fengari, a Lua VM written in JavaScript
  • WebAssembly with wasm_lua
  • lua.js compiles Lua directly to JavaScript. Has lower compatibility but lower footprint too.
  • moonshine

Fengari and Moonshine execute compiled Lua bytecode. They are more compatible than lua.js, and have a lower code-size footprint than e.g. an Emscripten-compiled Lua interpreter. They may be the slowest method of all because they aren't using WASM/asm.js like the stock Lua interpreter compiled with Emscripten would, and they aren't generating JavaScript which could be subsequently JIT'ed.

I'd try using Fengari first as it seems to be most active. It has easier JS interop than something using WASM would have.


On the WWW scripts can run in two places.

  1. In the web browser
  2. On the web server

If you want it to run in the browser, then you need support for the language built into the browser (or provided by an extension). For all practical purposes, if you are writing webpages for the WWW, then the only language you can use in an HTML <script> is JavaScript.

If you want to run it on the web server, then you need to get your HTTPD to run the script in response to a URL being requested from it. The simplest way to achieve this is via CGI.

With CGI, the HTTPD will run a program (as a separate process) in response to the request being made. It will pass in various information about the request via STDIN and environment variables (as described in the CGI specification). The script then prints an HTTP response (header (at least a Content-Type) and body (e.g. an HTML document)) and sends it to STDOUT where the HTTPD picks it up and sends it back to the browser.

How you configure your server to run programs using CGI depends on the server. Apache has a guide for their server.

There are probably CGI libraries for Lua, but I don't know the language so cannot make any recommendations.

CGI is a slow and inefficient protocol (as it requires a new processes to be spawned for each request). There are alternatives, such as FastCGI and various language specific options. Again, I don't know what is considered optimal in Lua land.

Tags:

Html

Browser

Lua