Caleb P
Caleb P

Reputation: 361

Using Lua from the Command Line With ... for Function

I've used Lua with Corona SDK for a long time, but I only just downloaded the standalone Lua interpreter (invoked from the command line). When I use

lua main.lua

From the Mac terminal, for some reason, any functions that use (...) no longer have access to arg as their ... arguments; rather, arg now points to the command line arguments.

My question: is there a way to invoke Lua from the command line and still have functions like

local function myFunction(...)
  print(arg[1])
end

With them pointing to the their own ... arguments, not the command line ones?

Upvotes: 1

Views: 280

Answers (1)

Kamiccolo
Kamiccolo

Reputation: 8497

What about saving those command line arguments on some variable or table just at the entry point? Example:

local function myFunction(...)
    print(cmd_arg)
end
-- Entry point:
local cmd_arg = arg[1]
myFunction()

or collecting all of command line arguments into table:

local function myFunction(...)
    print(cmd_arg[1])
end

-- Entry point:
local cmd_args = {}
for _, cmd_arg in arg do
    table.insert(cmd_args, cmd_arg)
end
myFunction()

EDIT: the solution is already mentioned here: https://stackoverflow.com/a/9787126/1150918

arg appears to be deprecated since 5.1.

And Michal Kottman's solution was:

function debug(name, ...)
    local arg = table.pack(...)
    print(name)
    for i=1,arg.n do
        print(i, arg[i])
    end
end

Upvotes: 1

Related Questions