Embedding Lua in Go

I embedded lua in my leatherman so that I could add even weirder features without too much effort. It was awesome.

In order to not stress about … everything … last night I decided that a sufficiently interesting and challenging task would be to embed a lua interpreter into my leatherman, such that my discord bot that reacts to messages with emoji could easily be driven without recompilation

It was tricky; maybe the hardest part being that there are at least three major implementations of lua in Go (an abandoned Lua 5.3 VM from microsoft, a 5.2 VM from shopify, and a 5.1 VM from some rando)

I ended up selecting the 5.1 VM because the interface was slightly simpler and the error messages were good. I’d be down to use the shopify one if I could get the error messages to be more clear.

The actual change is here. I should have written it with tests etc but I didn’t feel like it. I hope this is a safe space!

I documented the API a little this evening. For the first time I am thinking that a single generated README may be a mistake.

Here’s how my older data driven api looked:

  {
    "emoji": "🇳",
    "jsonre": "^cute",
    "required": true
  },
  {
    "emoji": "🇪",
    "jsonre": "^cute",
    "required": true
  },
  {
    "emoji": "🇦",
    "jsonre": "^cute",
    "required": true
  },
  {
    "emoji": "🇹",
    "jsonre": "^cute",
    "required": true
  },

Here’s how the newer lua driven api looks:

if es:messagematches("^neat") and not es:messagematches("^neat\\s*cute") then
        es:addrequired("🇨")
        es:addrequired("🇺")
        es:addrequired("🇹")
        es:addrequired("🇪")
end

I’ve wanted to do something like this for ages. It’s not often that scripting your code is warranted, but this felt like a pretty good use-case. A non-trivial reason is that I wanted to build in more weird easter eggs without my friends being able to read the code and anticipate them.

I know for a fact that there are things I could be doing to make the code faster, like only compile the script once, rather than each time a message is received. I might do a follow up post on that if I find it interesting enough.

Hope you enjoyed this as much as me!


(Affiliate links below.)

Recently Brendan Gregg’s Systems Performance got its second edition released. He wrote about it here. I am hoping to get a copy myself soon. I loved the first edition and think the second will be even more useful.

At the end of 2019 I read BPF Performance Tools. It was one of my favorite tech books I read in the past five years. Not only did I learn how to (almost) trivially see deeply inside of how my computer is working, but I learned how that works via the excellent detail Gregg added in each chapter. Amazing stuff.

Posted Thu, Jan 7, 2021

If you're interested in being notified when new posts are published, you can subscribe here; you'll get an email once a week at the most.