Base64 Encoding in Lua
Our first example demonstrates base64 encoding and decoding in Lua. Here’s the full source code:
-- We'll use the base64 module from LuaRocks
local base64 = require("base64")
-- Here's the string we'll encode/decode
local data = "abc123!?$*&()'-=@~"
-- Encode using standard base64
local sEnc = base64.encode(data)
print(sEnc)
-- Decode the standard base64 string
local sDec = base64.decode(sEnc)
print(sDec)
print()
-- Lua doesn't have a built-in URL-safe base64 encoder,
-- so we'll create a simple function to make it URL-safe
local function urlsafe_b64encode(s)
return (s:gsub('+', '-'):gsub('/', '_'))
end
local function urlsafe_b64decode(s)
return (s:gsub('-', '+'):gsub('_', '/'))
end
-- Encode using URL-safe base64
local uEnc = urlsafe_b64encode(base64.encode(data))
print(uEnc)
-- Decode the URL-safe base64 string
local uDec = base64.decode(urlsafe_b64decode(uEnc))
print(uDec)
This script uses the base64
module, which you can install using LuaRocks:
$ luarocks install base64
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:
$ lua base64_encoding.lua
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
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.