druidbruce

AEst userIo

Apr 25th, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. local MAX_OPTIONS = 13
  2.  
  3. function promptForNumber()
  4. local value = nil
  5. while value == nil do
  6. io.write("> ")
  7. value = tonumber(io.read())
  8.  
  9. if value == nil then
  10. print("ERROR: Invalid number. Please try again.")
  11. end
  12. end
  13.  
  14. return value
  15. end
  16.  
  17. function promptForNumberInRange(min, max)
  18. local value = nil
  19. while value == nil do
  20. local tValue = promptForNumber()
  21.  
  22. if tValue < min then
  23. print("ERROR: please enter a number >= " .. min)
  24. elseif tValue > max then
  25. print("ERROR: please neter a number <= " .. max)
  26. else
  27. value = tValue
  28. end
  29. end
  30.  
  31. return value
  32. end
  33.  
  34. function printOptions(options, banner)
  35. local page = 1
  36. local N = table.getn(options)
  37. local maxPage = math.ceil(N / MAX_OPTIONS)
  38. local viewing = true
  39.  
  40. while viewing do
  41. print(banner)
  42.  
  43. if N > MAX_OPTIONS then
  44. term.clear()
  45. term.setCursorPos(1, 1)
  46.  
  47. print(banner)
  48. print()
  49.  
  50. print(string.format(
  51. "Viewing %d items (%d/%d)",
  52. N,
  53. page,
  54. maxPage
  55. ))
  56. print("------------------------------------")
  57. end
  58.  
  59. local start = (((page - 1) * MAX_OPTIONS) + 1)
  60. for i = start, math.min(N, (start + MAX_OPTIONS - 1)), 1 do
  61. local option = options[i]
  62.  
  63. if type(option) == "table" then
  64. option = option.name
  65. end
  66.  
  67. print(string.format("%d. %s", i, option))
  68. end
  69.  
  70. if N <= MAX_OPTIONS then
  71. break
  72. else
  73. print("------------------------------------")
  74. io.write("[j] previous, [k] next, [Enter] done")
  75.  
  76. while true do
  77. local sEvent, key = os.pullEvent("key")
  78.  
  79. if key == keys.k then
  80. page = math.min(maxPage, page+1)
  81. break
  82. elseif key == keys.j then
  83. page = math.max(1, page-1)
  84. break
  85. elseif key == keys.enter then
  86. viewing = false
  87. break
  88. end
  89. end
  90. end
  91.  
  92. if not viewing then
  93. print()
  94. end
  95. end
  96. end
  97.  
  98. function chooseOption(options)
  99. printOptions(options)
  100.  
  101. local option = promptForNumberInRange(1, table.getn(options))
  102. return options[option]
  103. end
Add Comment
Please, Sign In to add comment