Weird error

Posted by Shadoweave on Mon 24 Sep 2007 06:22 AM — 3 posts, 15,871 views.

#0
When I run this script:

function change_settings (sName, sLine, wildcards)
settings[wildcards[1]] = tonumber(wildcards[2])
end -- function


the following script:

function prompt (sName, sLine, wildcards)
i = 1
  	repeat
    	if  tonumber (GetVariable ("c_"..healpriority[i])) < 
            tonumber( GetVariable( "max"..healpriority[i] ) ) * (settings[healpriority[i]]) then
			elixbal_aff[healpriority[i]] = hme_cure[healpriority[i]]
			i = 3
		end -- if
	i = i + 1
	until i > 3
elixbal_check ()
end -- function

keeps giving me this error:

[string "Script file"]:1644: attempt to perform arithmetic on field '?' (a nil value)
stack traceback:
	[string "Script file"]:1644: in function <[string "Script file"]:1622>

The error is on the "if" line, more specifically where I try to multiply. The weird thing is, when I reload the script file it works without any problems. I am baffled, any suggestions?
Amended on Mon 24 Sep 2007 06:58 AM by Nick Gammon
Australia Forum Administrator #1
tonumber returns nil if the string cannot be converted to a number, see:

http://www.gammon.com.au/scripts/doc.php?lua=tonumber

Since running change_settings causes the problem, I would look there. You could test that you have a valid number like this:


function change_settings (sName, sLine, wildcards)
  settings[wildcards[1]] = assert (tonumber(wildcards[2]), 
                           "wildcard '" .. tostring (wildcards [2]) .. "' is not a number")
end -- function


The "assert" function checks that its first argument is true (that is, not nil and not false) and if so, returns that as its result (thus you can use it in an assignment).

However if the assertion fails, you get an error message. The way I have worded it, you will see what wildcard 2 is, so you can see why it is becoming nil.
Amended on Mon 24 Sep 2007 06:59 AM by Nick Gammon
#2
You were right, that was the problem. The wildcards[2] variable was 1/4, and it wasn't interpreting it as a number, or as a string. If I use .5, it recognizes it as a number, so there is no need to use the "tonumber" function.