KaoSDlanor

advanced menu function

Nov 15th, 2012
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local function newmenu(tList,x,y,height)
  2.     local function maxlen(t)
  3.         local len=0
  4.         for i=1,#t do
  5.             local curlen=string.len(type(t[i])=='table' and t[i][1] or t[i])
  6.             if curlen>len then len=curlen end
  7.         end
  8.         return len
  9.     end
  10.    
  11.     local max=maxlen(tList)
  12.     x=x or 1
  13.     y=y or 1
  14.     y=y-1
  15.     height=height or #tList
  16.     height=height+1
  17.     local selected=1
  18.     local scrolled=0
  19.     local function render()
  20.         for num,item in ipairs(tList) do
  21.             if num>scrolled and num<scrolled+height then
  22.                 term.setCursorPos(x,y+num-scrolled)
  23.                 local current=(type(item)=='table' and item[1] or item)
  24.                 write((num==selected and '[' or ' ')..current..(num==selected and ']' or ' ')..(max-#current>0 and string.rep(' ',max-#current) or ''))
  25.             end
  26.         end
  27.     end
  28.     while true do
  29.         render()
  30.         local evts={os.pullEvent('key')}
  31.         if evts[1]=="key" and evts[2]==200 and selected>1 then
  32.             if selected-1<=scrolled then scrolled=scrolled-1 end
  33.             selected=selected-1
  34.         elseif evts[1]=="key" and evts[2]==208 and selected<#tList then
  35.             selected=selected+1
  36.             if selected>=height+scrolled then scrolled=scrolled+1 end
  37.         elseif evts[1]=="key" and evts[2]==28 or evts[2]==156 then
  38.             return (type(tList[selected])=='table' and tList[selected][2](tList[selected][1]) or tList[selected])
  39.         end
  40.     end
  41. end
Advertisement
Add Comment
Please, Sign In to add comment