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

menu:92: attempt to get length of nil

Started by RadiationAlert, 14 December 2014 - 02:03 AM
RadiationAlert #1
Posted 14 December 2014 - 03:03 AM
I keep getting the error menu:92: attempt to get length of nil, but I can't seem to understand why. I've even reviewed the tutorial I was watching (mainly to refresh my memory about ComputerCraft Lua), and the video seems to be exactly the same as my script.

PasteBin Link: http://pastebin.com/K1VgFaKC

If you can, please identify the error and report back why it isn't working.
Dragon53535 #2
Posted 14 December 2014 - 05:55 AM
I'm gonna copy where your program goes wrong, to why it goes wrong.


function Choice2 ()

  inLightsMenu = true
  selectedItem = 1

  while inLightsMenu do

	term.clear ()
	term.setCursorPos (1, 1)
  
	printMenu (lightsMenu) --#Line 34

	event, key = os.pullEvent ("key")

	onKeyPressed (key, lightsMenu)
  
  end

end

function LightsOn ()

  inLightsMenu = false

end

function LightsOff ()

  inLightsMenu = false

end

function Exit ()

  inMainMenu = false

end

---------------
-- Main Menu --
---------------

local mainMenu = {

  [1] = {text = "Choice 1", handler = Choice1},
  [2] = {text = "Choice 2", handler = Choice2},
  [3] = {text = "Exit"	, handler = Exit},

}

local lightsMenu = {

  [1] = {text = "Lights On" , handler = LightsOn},
  [2] = {text = "Lights Off", handler = LightsOff},

}

Your problem here, is that at line 34 you're calling the function printMenu and passing the lightsMenu table to it. However you're not defining lightsMenu until later.
The Lua interpreter sees that lightsMenu isn't defined at the moment it reads that function and then says it's going to have to look for the global lightMenu when i get there, however you are declaring lightsMenu as local, so it's never going to be the global lightsMenu. So you're passing nil the printMenu and it's erroring because it cannot get the length of a nil value.

An easy fix for this is to move your lightsMenu and mainMenu tables to the top of your code, so that every function in the program has access to it.
Edited on 14 December 2014 - 04:58 AM