Arguments that I pass to a lua script are nil

863 Views Asked by At

I am writing a Lua 5.3 program and it requires arguments to be passed to it. I use the arg table to get the first argument: arg[1], but the 1st argument, according to the script, is nil even though I have passed an argument to the file.

Here's the code that I've written:

local strin = arg[1]:sub(2,arg[1]:len()-1)   -- to remove the quote marks
local i = 0
for W in strin:gmatch(".") do
    i = i + 1
    if W == " " or W == "\t" then strin = strin:sub(i+1) else break end
end
print(strin)

I pass the argument to the file like this:

C:\Users\WhiteKid\Documents\Scripts>RemoveWhiteSpace.lua "     hello world!"

It thinks arg[1] is a nil value when it is not. Is there a different way of getting the arguments passed to a lua script in Lua 5.3?

1

There are 1 best solutions below

0
On BEST ANSWER

Since you are calling the .lua script directly (C:\Users\WhiteKid\Documents\Scripts>RemoveWhiteSpace.lua " hello world!"), you seem to have an association with a lua interpreter. You need to make sure you pass %1 or %* to the interpreter you are calling in that association. Alternatively, try calling the Lua interpreter and passing the script name and the parameters and it should work as you expect.

Also, you should check if arg[1] is present and check if the quotes are also there (as they may be removed before the parameters get to the script, so you should not always expect them).