Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Menu API
- -- by RichardG867
- local menu = {
- display = function(self)
- selCharLength = #self.selChar
- baseY = 0
- maxX, maxY = term.getSize()
- term.clear()
- term.setCursorPos(1,1)
- if self.title ~= nil then
- baseY = #self.title + 1
- for i = 1, #self.title do
- print(self.title[i]:sub(1, maxX-1))
- end
- end
- columns = math.ceil(#self.entries / (maxY - baseY))
- columnWidth = math.floor(maxX / columns)
- curColumn = 1
- entryOffset = {}
- entryRow = {}
- j = 1
- for i = 1, #self.entries do
- if baseY + j > maxY then
- curColumn = curColumn + 1
- j = 1
- end
- entryOffset[i] = (curColumn - 1) * columnWidth
- entryRow[i] = j
- if self.entries[i] ~= "" then
- term.setCursorPos(entryOffset[i] + selCharLength + 1, baseY + j)
- term.write(self.entries[i]:sub(1, columnWidth-selCharLength-1))
- end
- j = j + 1
- end
- curEntry = 1
- while curEntry > 0 and self.entries[curEntry] == "" do
- curEntry = curEntry + 1
- end
- if curEntry > #self.entries then error("Empty entry list") end
- while true do
- term.setCursorPos(entryOffset[curEntry] + 1, baseY + entryRow[curEntry])
- term.write(self.selChar)
- event, key = os.pullEvent("key")
- clearSel = 0
- if key == 200 then
- clearSel = curEntry
- curEntry = curEntry - 1
- while curEntry > 0 and self.entries[curEntry] == "" do
- curEntry = curEntry - 1
- end
- if curEntry < 1 then curEntry = clearSel end
- elseif key == 208 then
- clearSel = curEntry
- curEntry = curEntry + 1
- while curEntry <= #self.entries and self.entries[curEntry] == "" do
- curEntry = curEntry + 1
- end
- if curEntry > #self.entries then curEntry = clearSel end
- elseif key == 28 then
- term.clear()
- term.setCursorPos(1,1)
- return curEntry
- end
- if clearSel > 0 then
- term.setCursorPos(entryOffset[clearSel] + 1, baseY + entryRow[clearSel])
- term.write(string.rep(" ",selCharLength))
- end
- end
- end,
- setSelChar = function(self, char)
- self.selChar = char
- end,
- tostring = function(self)
- return "Menu["..#self.entries.."]"
- end
- }
- local metatable = {
- __index = menu,
- __tostring = menu.tostring
- }
- function new(title, entries)
- if entries == nil or #entries < 1 then
- error("Empty entry list")
- end
- local newmenu = {
- title = title or nil,
- entries = entries,
- selChar = "> "
- }
- setmetatable(newmenu, metatable)
- return newmenu
- end
Add Comment
Please, Sign In to add comment