This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Wedja's profile picture

attempt to call __sub at nil and number

Started by Wedja, 27 October 2012 - 09:39 PM
Wedja #1
Posted 27 October 2012 - 11:39 PM
Hi,

I wrote the following function:

function checkid(i, f)
  local tmp1
  local tmp2
  local pos
  file = io.open(f, "r")
  if file == nil then
	return 0
  end
  for line in file:lines()
  do
	pos = string.find(line, ";")
	tmp1 = string.sub(line, 0, pos - 1)
	tmp2 = string.sub(line, pos+1)
	if tmp1 == i then
	  file:close()
	  return tonumber(tmp2)
	end
  end
  file:close()
  return 0
end

at line
tmp1 = string.sub(line, 0, pos1 - 1)
I get the following error:
"attempt to perform arithmetic __sub on nil and number"
well, if I do a print(pos) before the line it prints me 3 and thats how it should be.
Can anyone tell me how to fix that?

Best Regards
Wedja
remiX #2
Posted 28 October 2012 - 12:23 AM

pos = string.find(line, ";")

pos = tonumber(string.find(line, ";"))

Try that
Lyqyd #3
Posted 28 October 2012 - 12:31 AM
No, that would be string and number. You need a fallback case in the event that the line doesn't contain a semicolon. Try encasing the rest of the operations in a block starting with if pos then, to ensure that pos is not nil.
Wedja #4
Posted 28 October 2012 - 09:12 AM
<p>Hi thank you for your answers,</p>
<p> </p>
<p>I added the if block and it didn&amp;#39;t crash, but the real bug was another. the variable &amp;quot;i&amp;quot; is a number so i had to change my if statemant to</p>
<pre class="prettyprint">
<span class="kwd">if</span><span class="pln"> tonumber(tmp1) </span><span class="pun">==</span><span class="pln"> i </span><span class="kwd">then

</span>
</pre>