r/lua • u/NoneBTW • May 14 '25
preprocessor in lua
I’ve been thinking about adding a simple attribute‑based “preprocessor” to Lua—something that runs at compile time to transform or wrap functions. You could use it for things like inlining tiny helpers, optimization ease of development etc.
I know Lua tends to favor minimalism and explicit idioms, so I’m curious whether this would feel too “un‑Lua‑like.” On the other hand, I think it could clean up repetitive boilerplate and boost performance in hot paths.
Below is a sketch of what the syntax might look like, along with some usage examples:
-- (1) Inline small functions into call sites
\@inline
function add(a, b)
return a + b
end
-- After preprocessing: calls to add(a, b) become (a + b) directly.
-- (2) Benchmark execution time of a function
\@benchmark
function heavy_work(n)
-- simulate work
for i = 1, n * 1e5 do end
end
-- At runtime, heavy_work(10) prints: [heavy_work] took 0.012s
-- (3) Memoize pure functions automatically
\@memoize
function fib(n)
if n < 2 then return n end
return fib(n-1) + fib(n-2)
end
-- fib(30) runs in O(n) instead of O(2^n).
-- (4) Register compile‑time callbacks
\@callable
function do_something_awesome()
print("Registered at compile time")
end
-- (5) Retry on error (e.g., network calls)
\@retry(3)
function fetch_data(url)
return http.get(url) -- might error
end
-- fetch_data retries up to 3 times before finally erroring.
-- (6) Initialization hook
\@init
function setup_environment()
print("Environment initialized!")
end
-- runs once, when the script is loaded.
-- (7) Documentation and metadata
\@doc("Calculates the nth Fibonacci number efficiently.")
\@todo("Add tail‑recursive version")
\@tag("math", "performance")
\@deprecated("Use fib_fast instead")
function fib(n)
-- …
endWhat do you think? I’d love to hear your thoughts and any ideas for useful annotations I haven’t listed!
6
u/SkyyySi May 14 '25
Unless implemented as a lua-language-server pluging, this would brick any static analysis tool, which makes it an immediate non-starter. Most things your sample uses pre-processing for can also be done using comment annotations with LLS. For the cases where it isn't, it could also just be done through a plain old function call.
Then there's also the issue of this being more complex than you're probably expecting. To get the features you're describing, a pre-processor would simply not cut it. You'd need a full Lua parser and compiler unless you want it to explode on the slightest touch. You cannot rely on just searching for the first occurance of
endon the same indentation level if that's what you wanted to do, since Lua doesn't actually care about whitespace outside of delimiting keywords and variable names.I fail to see how it would do either of these.
If you still want to do it: Keep in mind that it exists already https://github.com/ReFreezed/LuaPreprocess
3
u/appgurueu May 14 '25
I think there is some point in having macros (mostly for performance reasons), though by having first-class closures, coroutines, tables, and overall a language that does everything at runtime, it is very limited.
Your examples don't seem very well chosen to me though:
3
u/Amablue May 15 '25 edited May 15 '25
I toyed around with adding something like this a while back.
https://github.com/alexames/lua/blob/lx/5.5/feature/decorators-tests/testes/decorators.lua
(this is a file with tests/samples, but if you build this branch the interpreter will be able to parse and run the file)
It's not quite what you describe here, but it's pretty close. I added a decorator syntax similar to what other languages do, and used it to allow you to intercept variable assignments, with the most common use case being returning a new function that calls the original in some capacity, which you can use for things like memoizing or retry with exponential back off.
2
u/h2bx0r May 14 '25
Lua did have a "preprocessor", in the form of pragmas.
It was a thing in Lua 3.0, and removed in 4.0 with a cautionary warning.
For instance, this would work in Lua 3.2.2:
That would make the lexer stop abruptly.
Alternatively:
This would skip the print statement.
2
u/revereddesecration May 15 '25
It's a fun idea. What would the output of the memoize preprocessor be?
1
u/[deleted] May 14 '25
Inlining is only useful in loops where you do MANY calls or when functions are small (Go auto inlines small functions) and non recursive, So giving attributes to a function that it should be inline is useless in most cases, since you should be able to examine the code and see that its not recursive.
The only useful case for inlining is in loops, not all loops, only loops that are fast and run for a long time so the inline indicator should not be in the function but in loops. for i=1,1 is useless to inline but not in i=1,10000, there's also while loops, and repeat until which run however long, in which case, inline should be a keyword or an additive attribute/option for them @while @for @repeat
If you want to benchmark, you use benchmark(Function, ...) or debug.sethook on that function.
Yes, this might be useful, you could also make a memoizing closure so its unnecessary.
Lua already compiles everything, its why if you want dynamism you use tables and functions, everything outside a table or function will be compiled on load
You can just do function Retry(n, F, ...) local R for i=1,n do local R = {pcall(F, ...)} if R[1] then return table.unpack(R) end end error(table.unpack(R)) end Retry(3, Function, ...)
I think there's good news, lua5.5 might have on_error metatable as well. so that's nice.
This is unnecessary, lua already compiles and runs all the code that is outside functions on load() if you want more you make an Init() function or you can hijack the require so it calls Init() on import.
luadoc and lsp achieve this, I hate it, but since the output is an html file, its good to separate it.
1
u/dy895y-bd152XY-B2sIN May 17 '25
I'm doing a similar thing with a modified `load()` function that you can insert transformations into, which I use for things like profiling, inserting debug code, patching new language features into Lua with Lua at runtime, etc. Maybe it can help give some ideas.
1
u/lambda_abstraction May 14 '25 edited May 14 '25
fib is still slow. Should do log(n) operations. ;-)
Well at least it matters if you have bignums.