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

Issues with Tables and Their Lengths

Started by ComputerCraftUser, 28 May 2017 - 04:32 AM
ComputerCraftUser #1
Posted 28 May 2017 - 06:32 AM
Completed To-Do List Program Link: https://pastebin.com/Wnb72pGT

Pastebin link: https://pastebin.com/hTiXQP0W


monitor = peripheral.wrap("right")
monitor.clear()

local function screenRefresh()
monitor.clear()
monitor.setCursorPos(1,1)
local x, y = term.getCursorPos()
monitor.write("	 THE GRAND TODO LIST!")
y=y+1
monitor.setCursorPos(x,y)
  for i = 1,#Table do
	 monitor.write("Table[i]")
	 monitor.setCursorPos(x,y)
	 y=y+1
  end
end

local Table = {}

print(#Table)

local input = ""
local numin = 0
local taskin = ""
while true do
  print("What would you like to do?")
  print("1) Add new item.")
  print("2) Remove item.")
  print("3) Refresh List.")
  input = read()
  if (input == "1") and (#Table < 15) then
	print("New Item:")
	taskin = read()
	table.insert(Table, taskin)
	print(#Table)
   -- screenRefresh()
  elseif #Table > 15 then
	print("Sorry, the list is full!")
  end
  if (input == "2") then
	print("Which item should I remove?")
	numin = tonumber(read())
	table.remove(Table, numin)
	screenRefresh()
  end
  if (input == "3") then
	screenRefresh()
  end
end

Trying to figure out why any call to screenRefresh crashes with "monitor:11: attempt to get length of nil", even if the table (named Table) has elements manually inserted before running,

Any feedback/potential solutions would be greatly appreciated!
Edited on 28 May 2017 - 08:38 PM
Lyqyd #2
Posted 28 May 2017 - 06:59 AM
You need to declare Table above the function (and should probably use a different name for it), otherwise the function won't see it. The table must already be declared when you declare the function.
ComputerCraftUser #3
Posted 28 May 2017 - 06:49 PM
Thanks for your help Lyqyd, program works as intended now!