View difference between Paste ID: ikP8S39V and cKW626VM
SHOW: | | - or go back to the newest paste.
1-
--[[
1+
local function newmenu(tList,x,y,height)
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:
2+
	local function maxlen(t)
3-
3+
		local len=0
4-
newmenu({1,2,3,4},2,2)
4+
		for i=1,#t do
5-
5+
			local curlen=string.len(type(t[i])=='table' and t[i][1] or t[i])
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
6+
			if curlen>len then len=curlen end
7-
7+
8-
newmenu({1,{2,function(param) return print('you selected '..param) end},3,4},2,2)
8+
		return len
9-
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
10+
	
11-
]]
11+
	local max=maxlen(tList)
12-
12+
13-
local function newmenu(tList,x,y)
13+
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-
			term.setCursorPos(x,y+num)
20+
21-
			write((num==selected and '[' or ' ')..(type(item)=='table' and item[1] or item)..(num==selected and ']' or ' '))
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