Base64 Encoding in Lua
Our first example demonstrates base64 encoding and decoding in Lua. Here’s the full source code:
This script uses the base64
module, which you can install using LuaRocks:
Let’s break down the code:
We import the
base64
module.We define our input string
data
.We use
base64.encode()
to encode the string andbase64.decode()
to decode it back.Since Lua doesn’t have a built-in URL-safe base64 encoder, we create simple functions
urlsafe_b64encode()
andurlsafe_b64decode()
to convert between standard and URL-safe base64.We demonstrate URL-safe base64 encoding and decoding using these functions along with the standard base64 functions.
When you run this script, you should see output similar to this:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
), but they both decode to the original string as desired.
Note that in Lua, we had to create our own URL-safe base64 functions, as it’s not provided in the standard library. In a production environment, you might want to use a more robust implementation or a dedicated library for URL-safe base64 encoding.