f-string.lua
🦔 🦔 🦔
A Python-like f-string implementation for Lua.
You can play with it above by using f"fancy strings with variable interpolations: {1 + 2 = }"
in it and they should work exactly as you'd expect.
f = require("f-string")
local who = "hedgehogs"
print(f"hello {who}!")
Features
You can put any Lua expression into the f-string and it'll hopefully work.
=
endings are supported:
> f"{1 + 1 = }"
1 + 1 = 2
- Formatting specs support everything in
string.format
and can be used with:%
:
> f"{100:%.2f}"
100.00
Caveats
- Upvalue access is kinda broken: Variables from outer scopes of functions (upvalues) are only reliably accessible if they are referenced outside the f-string. For example:
local x = "outer scope"
local function inner()
-- This reference is needed for the upvalue to be accessible in the f-string
if x then end
local result = f"x = {x}" -- Now works correctly
end
- Uses
debug
so is probably slow as heck
Making-of
This was fun to make. Writing parsers is always good fun and the little one I hand-rolled here seems to do the job well enough, giving this handling for strings and comments that's a lot better than a regex-based approach. Writing up little parsers comes up a lot for me and previously I'd try to take care of the stack myself and only go character by character, but here I tried to use the function stack as the stack (hence all the parse local functions) for some recursive descent parser action, along with making it easier to take and check multiple characters ahead and it made for a pretty nice experience for me.
I did ask the computer to write test.lua
for me, which saved some time but was not as fun. It works though, I guess.