Search code examples
luaargumentsluajit

How to Disambiguate Command Line and Variable Arguments in Lua?


Specifically, Luajit. I am writing a script as a learning exercise and am attempting to use variable arguments. However, doing so just prints the command line arguments. I double-checked the documentation and, indeed, both applications use the arg variable.

How do I specify when I want to use one instead of the other?

function init(...)
    for k,v in pairs(arg) do print(k,v) end
    -- Function body.
end

Output,

0   /.../lua_script.lua
-1  luajit

Solution

  • LuaJIT, stemming from Lua 5.1, uses the newer vararg syntax, wherein you manually capture the varargs into a table:

    function init (...)
      local args = { ... }
      for k, v in pairs(args) do print(k, v) end
    end
    

    The special arg variable, in LuaJIT, is only used for command-line arguments.

    See the third item in the LuaJIT FAQ.