1

I am trying to parse extra arguments given to lualatex in command line — e.g lualatex --jobname=out in.tex myarg.

Though I could not find it in the docs, I discovered from this answer that I can use the arg variable to access command line arguments. However, these give me all arguments given to lualatex, including options and input file.

Currently my code looks something like this:

function get_args()
    arguments = {}
    reached_doc_arguments = false
    document_arg_position = -1
for index,argument in ipairs(arg) do
    if reached_doc_arguments then
        arguments[index - document_arg_position] = argument
    elseif argument:match("%.tex$") then
        document_arg_position = index
        reached_doc_arguments = true
    end
end
return arguments

end

However, this fails in cases where the .tex suffix is omited, and when options are given after the input file. I can't skip the first argument because options may be specified, and as mentioned, I can't use \jobname or status.filename.

I'm wondering if there is an intended, more complete way to do something like this?

1 Answers1

3

This is how LuaTeX parses its command line arguments:

  1. If the argument contains a backslash \, then treat it and all further arguments as TeX code
  2. If the argument starts with a dash -, treat it as a flag for the engine
  3. If the argument is the first argument that doesn't start with a backslash or a dash, treat it as a filename (with an implicit .tex if not present)
  4. Otherwise, ignore the argument

To capture only these final arguments that the engine ignores, you need to process the arguments the same way that the engine does. I believe that this code does what you want:

\documentclass{article}

\usepackage{luacode} \begin{luacode*} function get_args() local arguments = {} local filename_found = false

    for _, argument in ipairs(arg) do
        if argument:match("^%-") then -- Flags
            -- Ignore this argument
        elseif argument:match("\\") then -- Inline TeX code
            -- Ignore all following arguments
            break
        elseif not filename_found then
            filename_found = true
        else
            arguments[#arguments + 1] = argument
        end
    end

    return arguments
end

\end{luacode*}

\begin{document} Arguments: \directlua{ for _, argument in ipairs(get_args()) do tex.sprint(argument .. " ") end } \end{document}

Max Chernoff
  • 4,667
  • This is good, but it fails whenever a command line option takes an argument. Try to compile with (for example) --jobname out. The code will print the original filename as one of the arguments. – Atai Ambus Jul 08 '22 at 06:17
  • @AtaiAmbus Ah, that's a little trickier. If you use --jobname=out, it works, but to make it work with a space instead of = you'd probably need to hardcode every option that can take an argument. – Max Chernoff Jul 08 '22 at 06:39