| Lua code formatter | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Reformats Lua 5.5 source code to fit right margin. Strips comments. |
|
||||||||||||||
Initial version was relased in 2018. In 2026 I returned to this project and did following chnages:
-
No comments
Comments are not considered part of code.
-
No Luarocks
Now tool is self-sufficient file.
-
Changed scope
Tool is positioned as machine-level code viewer.
So no matter how bad and dirty is source code, it will reduce it to some canonic form.
Back side is that it will make code that you like look worse.
Feel free to tweak formatting routines to your taste but keep in mind that visual niceness is not in flight plan.
Repository contains
- Compiled code in
deploy/ - Sample input/output in
test/ - Complete source code in
src/ - Rebuild script and tools in
builder/
- Linux
- Lua 5.5 (5.4, 5.3).
$ lua reformat.lua
Reformat Lua 5.5 code.
Usage: f_in f_out
┬ ┬ ┬
│ │ │
└── [options] ─┘
<options>:
--indent=<str> Use given string as indent chunk.
--right-margin=<int> Right margin.
-- Martin, 2026-10
Suppose you have a string with Lua code and wish to get another string with formatted code.
do
local lua_code_str = 'do return end' -- < fill it
require('workshop.base')
local reformat = request('!.lua.code.reformat')
return reformat(lua_code_str)
endYou may override default parameters by passing a table with new values of changed parameters:
reformat(
lua_code_str,
{
indent_chunk = ' ',
right_margin = 72,
}
)| Parameter | Default | Description |
|---|---|---|
indent_chunk |
|
String used for building one indent. |
right_margin |
72 | Maximum line length with indent. |
First, general workflow of this formatter:
- Load
.luafile as string. - Parse that string to tree in table.
- Change nodes of that tree to make it easier to handle in formatting routines.
- Run formatting routines for all nodes in tree. Formatting routines output to virtual printer.
- Write contents of virtual printer to file.
We are at point 4. Start tinkering from something simple but usable
as "repeat" block handling:
workshop/concepts/lua/formatter/handlers/statements/blocks/repeat_block.lua
workshop-- My personal Lua framework- My other projects