4
votes

I have a lua redis script that I want to pass some nil arguments to in ARGV. I figured the following would work:

redis-cli EVAL "$(cat some_script.lua)" 3 key1 key2 key 3 nil nil 4

In that case, I'd expect ARGV[1] = ARGV[2] = nil. Instead, they seem to be set to 'nil' (the string) inside lua, so when I do something like:

if ARGV[1] then return ARGV[1] end

I get 'nil' returned to me.

How do I properly pass nils to Lua?

1
Don't pass anything and it'll be nil inside the program. Otherwise, you'll always receive a string. - hjpotter92
@hjpotter92 yes, but the question (and the example) are for when there's a non-nil argument after the nil argument. In that case, how would I pass nothing for the arguments that should be nil? See the example. - Eli

1 Answers

4
votes

No, command line arguments will always be a string, even if you pass arguments like this:

lua script.lua "test argument" "" "end"

You will still get

argv[1] = "test argument"
argv[2] = ""   --empty string
argv[3] = "end"

In this case, argv[4] = nil, but I don't think this is what you want, as the program expects a non-nil argument at the end.

So why not set some flag strings to stand for nil in your script, e.g, use the string "nil" as a flag, so you can test in your script:

if argv[1] ~= "nil" then return argv[1] end