Advertisement
koki2000

Clickable and keypress menu

Oct 31st, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.49 KB | None | 0 0
  1. w, h = term.getSize()
  2. run = true
  3. selitem = 1
  4.  
  5. function choice1()
  6.  print("choice1") sleep(1)
  7. end
  8.  
  9. function choice2()
  10.  print("choice2") sleep(1)
  11. end
  12.  
  13. function exiting()
  14.  print("exiting")
  15.  run = false
  16. end
  17.  
  18. mainmenu = {
  19. [1] = {text = "choice1", handler = choice1},
  20. [2] = {text = "choice2", handler = choice2},
  21. [3] = {text = "exit", handler = exiting}
  22. }
  23.  
  24. function printmenu(menu)
  25.  term.clear()
  26.  for i = 1, #menu do
  27.   local hossz = string.len(menu[i].text)
  28.   if i == selitem then
  29.    term.setCursorPos(w/2-(hossz/2), i)
  30.    term.setBackgroundColor(colors.red)
  31.    print(">"..menu[i].text.."<")
  32.   else
  33.    term.setCursorPos(w/2-(hossz/2), i)
  34.    term.setBackgroundColor(colors.brown)
  35.    print(" "..menu[i].text.." ")
  36.   end
  37.   term.setBackgroundColor(colors.black)
  38.  end
  39. end
  40.  
  41. function onkeypressed(key, menu)
  42.  if key == 28 then
  43.   menu[selitem].handler()
  44.  elseif key == 200 then
  45.   if selitem > 1 then
  46.    selitem = selitem - 1
  47.   end
  48.  elseif key == 208 then
  49.   if selitem < #menu then
  50.    selitem = selitem + 1
  51.   end
  52.  end
  53. end
  54.  
  55. function click(i, y)
  56.  if i == y then
  57.   return true
  58.  end
  59.   return false
  60. end
  61.  
  62. while run do
  63.  printmenu(mainmenu)
  64.  local event, par1, par2, par3 = os.pullEventRaw()
  65.  if event == "key" then
  66.  printmenu(mainmenu)
  67.   onkeypressed(par1, mainmenu)
  68.  elseif event == "mouse_click" then
  69.   for i = 1, #mainmenu do
  70.    if click(i, par3) then
  71.     if i ~= selitem then
  72.      selitem = i
  73.     else
  74.      mainmenu[selitem].handler()
  75.     end
  76.    end
  77.   end
  78.  end
  79. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement