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

Selector Menu

Started by grand_mind1, 01 February 2014 - 02:07 AM
grand_mind1 #1
Posted 01 February 2014 - 03:07 AM
I'm working on a selector menu for my tunnel program. I want it to be so you use the arrow keys to move up and down a list and then press enter to change the value of the thing you have selected. This is what I have so far:
http://pastebin.com/dHr8MNcL

However, for some reason the pressing enter part doesn't work for all of them. It only works for the first selection. I do not know why this is.
Help is appreciated.
Thanks! :D/>

Also, if someone thinks they know of a better way to do what I am trying to do, please tell. :)/>
Edited on 01 February 2014 - 02:11 AM
Bomb Bloke #2
Posted 01 February 2014 - 04:20 AM
On line 50, we have:

  elseif key == 28 and sel == 1 then

You really want that to just be:

  elseif key == 28 then

The keys API is filled with constants that allow you to make such code just a little more readable. For example, you could also use:

  elseif key == keys.enter then

A few other pointers: Instead of having a long list of "clear()"s throughout the script, why not just have the "drawMenu()" function do it?

When the user pushes up/down, instead of having two checks each for each button press, you could combine them into something like this:

  if key == keys.up then
    sel = sel - 1
    if sel == 0 then sel = #options end  -- Or you could use "if sel == 0 then sel = 1 end", if you prefer.
  elseif key == keys.down then
    sel = sel + 1
    if sel > #options then sel = 1 end   -- Or you could use "if sel > #options then sel = #options end", if you prefer.
  etc

… where "#options" returns the number of entries in your "options" table.

"for" loops are worth looking into. If you also stored your booleans in a table, you could use one to condense your "drawMenu()" function somewhat:

options={ --This begins my options table.
  "Use Torches:",
  "Use chests:",
  "Use Enderchests:",
}

bools = {false,false,false} -- Instead of using the "torch"/"chest"/"ender" variables, let's use this table.

function drawMenu() --Function where I draw the menu on the screen.
  for i=1,#options do
    if sel == i then write("*")  -- Unlike "print", "write" doesn't automatically go down a line.
    print(options[i].." "..tostring(bools[i]))
  end
end

You may be able to see how this also leads to condensing your checks when the user presses return on something.