KaoSDlanor

MutiColumn menu function

Nov 15th, 2012
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local function menu(opts,x1,y1,x2,y2,offset)
  2.     local x,y=term.getSize()
  3.     x1=x1 or 1
  4.     y1=y1 or 1
  5.     x2=x2 or x-1
  6.     y2=y2 or y-1
  7.     offset=offset or 1
  8.     s=1
  9.     sc=0
  10.    
  11.     local function maxlen(t)
  12.         local len=0
  13.         for num,ref in ipairs(opts) do
  14.             local item=(type(ref)=='table' and ref[1] or ref)
  15.             if len<#item then len=#item end
  16.         end
  17.         return len
  18.     end
  19.    
  20.     local function render()
  21.         local max=maxlen(opts)+2
  22.         local columns=math.floor(x2/(max+offset))
  23.         local curcol=0
  24.         local line=0
  25.         for num,ref in ipairs(opts) do
  26.             curcol=(curcol+1>columns and (function() line=line+1 return 1 end)() or curcol+1)
  27.             if line>=sc and y2+sc>=line+1 then
  28.                 term.setCursorPos(x1+(curcol-1)*(max+offset),y1+line-sc)
  29.                 local item=(type(ref)=='table' and ref[1] or ref)
  30.                 write((num==s and '[' or ' ')..item..(num==s and ']' or ' ')..(#item+2<max and string.rep(' ',max-#(item+2)) or ''))
  31.             end
  32.         end
  33.         return columns
  34.     end
  35.    
  36.     while true do
  37.         local cols=render()
  38.         local rows=math.ceil(s/cols)
  39.         local evts={os.pullEvent()}
  40.         if evts[1]=='key' and evts[2]==208 then
  41.             s=(s+cols<=#opts and s+cols or #opts)
  42.         elseif evts[1]=='key' and evts[2]==200 then
  43.             s=(s-cols>=1 and s-cols or 1)
  44.         elseif evts[1]=='key' and evts[2]==203 and s>1 then
  45.             s=s-1
  46.         elseif evts[1]=='key' and evts[2]==205 and s<#opts then
  47.             s=s+1
  48.         elseif evts[1]=='key' and evts[2]==28 then
  49.             return (type(opts[s])=='table' and opts[s][2](opts[s][1]) or opts[s])
  50.         end
  51.         if math.ceil(s/cols)>sc+y2 then sc=math.ceil(s/cols)-y2 end
  52.         if math.ceil(s/cols)<=sc then sc=math.ceil(s/cols)-1 end
  53.     end
  54. end
  55.  
  56. term.clear()
  57. term.setCursorPos(1,1)
  58. menu({'hello1','hello2','hello3','hello4','hello5','hello6'},2,2,20,2)
Advertisement
Add Comment
Please, Sign In to add comment