Enhance shebang handling in REPL and source code execution to preserve line numbers

This commit is contained in:
2025-10-09 16:35:22 +01:00
parent 27dfa57a5d
commit cf19a6ec5d
2 changed files with 54 additions and 8 deletions

41
luash
View File

@@ -133,7 +133,12 @@ function start_repl()
-- Luash preprocessing function for REPL
local function preprocess_luash_repl(code)
code = code:gsub("^#![^\r\n]*[\r\n]?", "") -- Remove shebang
-- Remove shebang line if present and preserve line numbers
local has_shebang = code:match("^#!")
code = code:gsub("^#![^\r\n]*[\r\n]?", "")
if has_shebang then
code = "\n" .. code
end
code = process_env_vars_repl(code)
code = process_interactive_commands_repl(code)
code = process_shell_commands_repl(code)
@@ -320,9 +325,15 @@ end
local source_code = file:read("*a")
file:close()
-- Remove shebang line if present
-- Remove shebang line if present and preserve line numbers
local has_shebang = source_code:match("^#!")
source_code = source_code:gsub("^#![^\r\n]*[\r\n]?", "")
-- If we removed a shebang, add an empty line to preserve line numbers
if has_shebang then
source_code = "\n" .. source_code
end
-- Preprocessing functions
@@ -466,18 +477,32 @@ source_code = process_env_vars(source_code)
source_code = process_interactive_commands(source_code)
source_code = process_shell_commands(source_code)
-- Combine and execute
local final_code = injected_lib .. "\n" .. source_code
-- Debug output
if os.getenv("LUASH_DEBUG") then
print("-- Generated Lua code:")
print(final_code)
print(source_code)
print("-- End generated code")
end
-- Execute
local func, err = load(final_code, "@" .. filename)
-- Pre-load injected library into global environment
if injected_lib ~= "" then
local lib_func, lib_err = load(injected_lib, "@__injected_lib.lua")
if lib_func then
local success, result = pcall(lib_func)
if not success then
print("--- ERROR loading injected library ---")
print(result)
return
end
else
print("--- SYNTAX ERROR in __injected_lib.lua ---")
print(lib_err)
return
end
end
-- Execute the user's source code (with correct line numbers)
local func, err = load(source_code, "@" .. filename)
if not func then
print("--- SYNTAX ERROR in " .. filename .. " ---")
print(err)

21
new_proj.luash Normal file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env luash
-- Environment variables (clean syntax)
print("Hello " .. $USER .. "!")
-- Variable assignment
$MY_VAR = "some value"
-- Shell commands with backticks
files = `ls -la`
current_dir = `pwd`
-- Interactive commands
!ls
-- The power of Lua + shell
if `test -f README.md` ~= "" then
lines = `wc -l < README.md`
print("README has " .. lines .. " lines")
end