Bad argument #2 (number expected, got nil)

In one of my scripts I have a function:

local function find_in_string(s, pattern)
	return string.sub(s, string.find(s, pattern))
end

and I call it with:

find_in_string(pack_data, constants.DESC_PATTERN)

constants.DESC_PATTERN being

 "class=\"description\">.<p>%w+"

When I run the program, it shows the error:

ERROR:SCRIPT: /main/test.script:112: bad argument #2 to 'find_in_string' (number expected, got nil)
stack traceback:
	[C]: in function 'find_in_string'
	/main/test.script:112: in function </main/test.script:41>

even though argument #2 is clearly not nil.

Did you require your “constants”?

What is the #2 argument then? Print this constants.DESC_PATTERN to check this out and as @COCO asked - check if you have your module required in the script:

local constants = require "path.to.your.module"

Or more likely you would like to make it required globally - just don’t use “local” word - require it once in a main script and then use it everywhere :wink:

Yes, and it works fine in the rest of my code.

It printed out exactly what I defined it as. I’ve also double-checked that everything is spelled correctly.

string.find return nil,if no pattern finded

4 Likes