Posted 26 February 2015 - 07:40 PM
messy, inefficient code
local maxx, maxy = term.getSize()
local scrollBar = function( content, offset )
local barSize = (maxy / (#content*5) * maxy)
for i = 1, maxy do
if i >= math.abs( offset/(#content*5/maxy) ) and i <= math.abs( offset/(#content*5/maxy) ) + barSize + 1 then
term.setBackgroundColor( colors.gray )
else
term.setBackgroundColor( colors.lightGray )
end
term.setCursorPos( maxx, i )
term.write( " " )
end
end
local display = function( content, offset )
term.setBackgroundColor( colors.white )
term.clear()
term.setBackgroundColor( colors.lightGray )
term.setTextColor( colors.gray )
for i = 1, #content do
local x, y = math.ceil((maxx - #content[ i ])/2), i * 5 - 2 + offset
term.setCursorPos( x - 1, y )
term.write( " " .. content[ i ] .. " " )
term.setCursorPos( x - 1, y - 1 )
term.write( string.rep( " ", #content[ i ] + 2 ) )
term.setCursorPos( x - 1, y + 1 )
term.write( string.rep( " ", #content[ i ] + 2 ) )
end
scrollBar( content, offset )
end
function scroll( ... )
local content = {...}
local offset = 0
local minScroll = maxy - (#content * 5)
local barClicked = true
local lastx, lasty
display( content, offset )
while true do
local event = {os.pullEvent()}
if event[ 1 ] == "mouse_scroll" then
offset = offset - event[ 2 ]
if offset > 0 then
offset = 0
elseif offset < minScroll then
offset = minScroll
end
display( content, offset )
elseif event[ 1 ] == "mouse_click" then
barClicked = false
--check buttons
for i, v in ipairs( content ) do
local x, y = math.ceil((maxx - #v)/2), i * 5 - 2 + offset
if event[ 3 ] >= x-1 and event[ 3 ] <= x + #v and event[ 4 ] >= y - 1 and event[ 4 ] <= y + 1 then
return v
end
end
--check scrollbar
if event[ 3 ] == maxx and event[ 4 ] >= math.abs( offset/(#content*5/maxy) ) and event[ 4 ] <= math.abs( offset/(#content*5/maxy) ) + (maxy / (#content*5) * maxy) + 1 then
barClicked = true
lastx, lasty = event[ 3 ], event[ 4 ]
end
elseif event[ 1 ] == "mouse_drag" and barClicked then
offset = offset + (event[ 4 ] - lasty)
lastx, lasty = event[ 3 ], event[ 4 ]
end
end
end
local var = scroll( unpack( fs.list( "/" ) ) )
term.clear()
term.setCursorPos( 1, 1 )
term.write( var )
Everything works normally, until I try to drag the scroll bar. I will later have to change the amount added/subtracked, but for now I'd just like it to increment offset.
I'd guess it's this line that's the problem:
if event[ 3 ] == maxx and event[ 4 ] >= math.abs( offset/(#content*5/maxy) ) and event[ 4 ] <= math.abs( offset/(#content*5/maxy) ) + (maxy / (#content*5) * maxy) + 1 then