This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
cocotoffee's profile picture

Trying to Cycle Pages

Started by cocotoffee, 31 December 2016 - 06:51 PM
cocotoffee #1
Posted 31 December 2016 - 07:51 PM
Hello,
I'm trying to create a list of pages to load with the touchpoint API and then cycle through them so I can scroll through the pages like the next or previous buttons in an online book. Here is the basic code I am trying to get to work:


os.loadAPI("touchpoint")
monitor = peripheral.wrap("left")

local a = touchpoint.new("left")
local b = touchpoint.new("left")
local currentPage = a

function nextPage()
  local pageList = 'ab'
  local index = pageList:find(currentPage)
  if index then
	currentPage = index + 1
  end
  currentPage:draw()
end

a:add("--->", function() nextPage() end, 1, 1, 10, 10, colors.red, colors.green)
b:add("placeholder", nil, 1 ,1 , 10, 10, colors.red, colors.green)
currentPage:draw()
currentPage:run()


When I try to run the code it draws the first button and sets up the pages. However, when I try to click the button and proceed to the next page, it gives an error saying that on line 10, it is expecting a string but receiving a table. I do not know how to convert what the current page is into a string so it can run. I have tried using concat and serialize/unserialize, but neither way works and I'm not sure how to do it. Thank you.
Lyqyd #2
Posted 31 December 2016 - 08:30 PM
You should put your pages in a table, then use a numeric index to point at the current page. You also won't be able to use the :run() method on the pages, since it will never change which one is being run.


local pages = {
  touchpoint.new("left"),
  touchpoint.new("left"),
}

local index = 1

local function nextPage()
  index = math.min(index + 1, #pages)
end

local function prevPage()
  index = math.max(index - 1, 1)
end

page[1]:add("--->", nextPage, 1, 1, 10, 10, colors.red, colors.green)
page[2]:add("<---", prevPage, 1, 1, 10, 10, colors.red, colors.green)

while true do
  pages[index]:draw()
  local event = {pages[index]:handleEvents(os.pullEvent())}
  if event[1] == "button_click" then
    if pages[index].buttonlist[event[2]].func then
      pages[index].buttonlist[event[2]].func()
    end
  end
end

Or something like that.
cocotoffee #3
Posted 31 December 2016 - 10:18 PM
Thank you so much for the response! I appreciate it. I tried using the code you pasted, and it gives an error regarding the line with the second if statement (line 23 of your example), saying it is trying to index a nil value. Would you be able to explain why it is doing that and possibly how to fix it? Thank you.
Lyqyd #4
Posted 01 January 2017 - 12:41 AM
That line and the line below it should have buttonList where they have buttonlist.
cocotoffee #5
Posted 01 January 2017 - 07:55 AM
Thank you so much for the help! That was the indeed the problem. Happy New Years.