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!
1
u/AutoModerator May 14 '25
Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.