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

Supposedly simple tables?

Started by toblerone321, 30 May 2014 - 07:38 PM
toblerone321 #1
Posted 30 May 2014 - 09:38 PM
I have been having a problem with a simple piece of code(or so i thought) to display a table which can be remotely edited.

term.clear()
local tFlights = {}
rednet.open("left")
while true do
  term.setCursorPos(1,1)
  id,message = rednet.receive()
  if message == "departed" then
	tFlights[1] = nil
	term.clear()
	for i, o in ipairs(tFlights) do
	  print(i, "	 ", o)
	end
  else
	table.insert(tFlights, message)
	term.clear()
	for i, o in ipairs(tFlights) do
	  print(i, "	 ", o)
	end
  end
end
In theory, this code should display an empty screen, until a rednet message arrives, and then the contents of the message should be appended to the table, the terminal cleared and the contents of the table, with key numbers, redrawn. If the message contains just "departed" then the first item in the table should be removed and the table redrawn.

What actually happens is as expected, until I send the message containing "departed", at which point the screen clears, but the table doesn't redraw, it just stays blank. Why is this?

Before "departed":



After "departed":
Lyqyd #2
Posted 30 May 2014 - 10:12 PM
You need to use table.remove(tFlights, 1) instead. That way, the other indexes will be shifted up to fill the gap, so the value at index 2 will move up to index 1, etc. Otherwise, ipairs looks at 1, sees that it is nil, and is done, so the loop goes through no iterations.
TheOddByte #3
Posted 30 May 2014 - 10:34 PM
To show what Lyqyd just said in code

You should change this part

tFlights[1] = nil
term.clear()
for i, o in ipairs(tFlights) do
	print(i, "	 ", o) -- it will error here since it's trying to print a nil value
end
into this

table.remove( tFlights, 1 )
term.clear()
for i, o in ipairs(tFlights) do
	print(i, "	 ", o)
end

Because your monitor will currently be clear with the code your running when receiveing a rednet message, But if you go and check the terminal it probably says 'attempt to index: a nil value' or something like that :P/>
Edited on 30 May 2014 - 08:35 PM
toblerone321 #4
Posted 31 May 2014 - 08:26 AM
Thanks both for your replies, it does indeed sound simple when it is explained to me! Thanks again
Toblerone