Lua is fun. And while I like that it's not part of very complicated web browser tech or something, being able to run it in the browser can be kind of nice. I like using it for example code in posts. And I like having examples that can be run and maybe modified on the page:
I've done some cleaning up of the code I use for this and put it in a repo. It's set up so that it deploys a couple of examples to GitHub pages.
The Lua implementation is C code that compiles pretty easily and you can Emscipten-compile it to wasm. I don't really know my way around that kind of stuff, but I found a wasm_lua repo on GitHub, and that had dealt with the stuff I didn't know how to do. I've made some small changes to the main.c
file and made different example pages, but my repo is mostly just that repo.
There's a C program that consist of Lua and a main.c
with:
run_lua
function that takes a string from the JS side and lets Lua compile and run it. run_lua
sets up the Lua VM the first time it's called.lua_web_send
function for sending a couple of strings to the JS sideThe idea is that the JS side is the most infrastructury side:
run_lua
function. It might do stuff like printing the payload with console.log
if the code is "log"
, or treat it as HTML and render it into the page somewhere if the code is "html"
.The Lua code is usually more "core domain" code. The code that is written in a REPL or used as example code in a post. The lua_web_send
C function is available in Lua as the webSend
Lua function. In the initialization code I typically replace it with a web
table that I do some metatable stuff to so I can e.g. do web.html("<p>hello</p>")
in order code "web"
and payload "<p>hello</p>"
to the JS side.
If something is more complicated than just sending a message to the JS side, I can add functions to web
manually. I have a web.require
that does some coroutine stuff so that it can send the code "require"
along with a URL to the JS side and then suspend the coroutine before the C function returns control to the JS side. The JS can then make the HTTP request to get the source code for the required library and send it to the Lua side in a way that resumes the suspended coroutine and loads the library. There's a bit of juggling but like it's fun.
Blep.