KaoSDlanor

basic menu function

Nov 15th, 2012
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.64 KB | None | 0 0
  1. --[[
  2. call newmenu with a table as the first parameter, the table is a list of all options in the menu, if you like you can specify a table as one/more of the options, it will then show the first value in that table as the choice and will call the second value as a function if you select that option, it will call the function with the option as a parameter and the newmenu function will return whatever your choice returns. if the choice is not a table then it will simply return the string that is the choice. example:
  3.  
  4. newmenu({1,2,3,4},2,2)
  5.  
  6. would generate a menu where you can choose 1; 2; 3 or 4 and if you choose 2 it will return 2. the menu will start at CDS 2,2
  7.  
  8. newmenu({1,{2,function(param) return print('you selected '..param) end},3,4},2,2)
  9.  
  10. would generate an identical looking menu but this time if you select 2 it will call the function there with param=2 and the newmenu function will return whatever the function returns
  11. ]]
  12.  
  13. local function newmenu(tList,x,y)
  14.     x=x or 1
  15.     y=y or 1
  16.     y=y-1
  17.     local selected=1
  18.     local function render()
  19.         for num,item in ipairs(tList) do
  20.             term.setCursorPos(x,y+num)
  21.             write((num==selected and '[' or ' ')..(type(item)=='table' and item[1] or item)..(num==selected and ']' or ' '))
  22.         end
  23.     end
  24.     while true do
  25.         render()
  26.         local evts={os.pullEvent('key')}
  27.         if evts[1]=="key" and evts[2]==200 and selected>1 then
  28.             selected=selected-1
  29.         elseif evts[1]=="key" and evts[2]==208 and selected<#tList then
  30.             selected=selected+1
  31.         elseif evts[1]=="key" and evts[2]==28 or evts[2]==156 then
  32.             return (type(tList[selected])=='table' and tList[selected][2](tList[selected][1]) or tList[selected])
  33.         end
  34.     end
  35. end
Advertisement
Add Comment
Please, Sign In to add comment