local M = {}
local STYLUA_PATH = "E:/Softwares/stylua-windows-x86_64/stylua.exe"
local function ends_with(str, suffix)
return str:sub(-#suffix) == suffix
end
local function is_lua_file(path)
return ends_with(path, ".lua")
or ends_with(path, ".script")
or ends_with(path, ".gui_script")
or ends_with(path, ".render_script")
end
local function format_file(path)
local local_path = "." .. path
local ok, result_or_err = pcall(
editor.execute,
STYLUA_PATH,
"--search-parent-directories",
local_path,
{
reload_resources = true,
out = "capture",
err = "stdout"
}
)
if not ok then
editor.ui.show_dialog(editor.ui.dialog({
title = "StyLua Error",
content = editor.ui.label({
text = tostring(result_or_err)
}),
buttons = {
editor.ui.dialog_button({
text = "OK",
default = true,
result = "ok"
})
}
}))
end
end
function M.get_commands()
return {
editor.command({
label = "Format Lua (StyLua)",
locations = { "Edit", "Assets" },
query = {
selection = {
type = "resource",
cardinality = "one"
}
},
active = function(opts)
local path = editor.get(opts.selection, "path")
return is_lua_file(path)
end,
run = function(opts)
editor.save()
local path = editor.get(opts.selection, "path")
format_file(path)
end
})
}
end
return M
How to use it?
step1: copy this editor_script to your project directory
I just added one line of code to M.get_commands() function to implement this handy feature.
stylua.editor_script
local M = {}
local STYLUA_PATH = "E:/Softwares/stylua-windows-x86_64/stylua.exe"
local function ends_with(str, suffix)
return str:sub(-#suffix) == suffix
end
local function is_lua_file(path)
return ends_with(path, ".lua")
or ends_with(path, ".script")
or ends_with(path, ".gui_script")
or ends_with(path, ".render_script")
or ends_with(path, ".editor_script")
end
local function format_file(path)
local local_path = "." .. path
local ok, result_or_err = pcall(
editor.execute,
STYLUA_PATH,
"--search-parent-directories",
local_path,
{
reload_resources = true,
out = "capture",
err = "stdout"
}
)
if not ok then
editor.ui.show_dialog(editor.ui.dialog({
title = "StyLua Error",
content = editor.ui.label({
text = tostring(result_or_err)
}),
buttons = {
editor.ui.dialog_button({
text = "OK",
default = true,
result = "ok"
})
}
}))
end
end
function M.get_commands()
return {
editor.command({
id = "format_lua_stylua", -- I added a id for keymap
label = "Format Lua (StyLua)",
locations = { "Edit", "Assets" },
query = {
selection = {
type = "resource",
cardinality = "one"
}
},
active = function(opts)
local path = editor.get(opts.selection, "path")
return is_lua_file(path)
end,
run = function(opts)
editor.save()
local path = editor.get(opts.selection, "path")
format_file(path)
end
})
}
end
return M