问题
Say I call Lua with this cmd:
luajit neuralnetwork.lua --satEpoch "somestring" --maxEpoch 50
How can I access this same cmd-line string from Lua?
I know about the arg
table, but it removes all quotes from the original command string making it difficult to reconstruct:
{
"--maxEpoch"
"--satEpoch"
"50"
"somestring"
[-1] : "luajit"
[0] : "examples/neuralnetwork.lua"
}
If I can save the exact string to a file from within Lua, I can easily call it again later.
回答1:
@peterpi is correct that the shell is interpreting the command and as a result stripping away the quotes. However, reconstructing the command exactly is not really necessary to have the shell interpret the command the same way as before.
For simple cases concatenating the arguments to the script is often enough:
local command = table.concat(arg, ' ', -1, #arg)
This will fail if the quotes are actually necessary, most commonly when an argument contains a space or shell character, so quoting everything is easy and somewhat more robust, but not pretty.
Here is an example with a Lua pattern to check for special (bash) shell characters and spaces to decide if and which quotes are necessary. It may not be complete but it handles filenames, most strings, and numbers as arguments.
local mod_arg = { }
for k, v in pairs(arg) do
if v:find"'" then
mod_arg[k] = '"'..v..'"'
elseif v:find'[%s$`><|#]' then
mod_arg[k] = "'"..v.."'"
else
mod_arg[k] = v
end
end
local command = table.concat(mod_arg, ' ', -1, #mod_arg)
print(command)
回答2:
No doubt somebody will prove me wrong, but generally I don't think this is possible. It's the shell rather than luajit that takes the quotes away and chops the line up into individual tokens.
来源:https://stackoverflow.com/questions/32379841/lua-cmd-line-string