-- inv_client_loop.lua (Advanced Wireless Pocket Computer)
local PROTO = "inv"
local REFRESH = 2 -- seconds
local side = peripheral.getName(peripheral.find("modem")) or error("no modem")
rednet.open(side)
local items, top = {}, 1
local function fetch()
rednet.broadcast("list", PROTO)
local id, resp = rednet.receive(PROTO, 3)
if id and type(resp) == "table" then items = resp end
end
local function draw()
term.clear()
term.setCursorPos(1,1)
print(("Items (%d) — %s"):format(#items, textutils.formatTime(os.clock(), true)))
print(("-"):rep(28))
local w,h = term.getSize()
local visible = h - 3
for i = 0, visible-1 do
local row = items[top + i]
if not row then break end
term.setCursorPos(1, 3 + i)
print(("%-24s x%d"):format(row.name or "?", row.count or 0))
end
term.setCursorPos(1, h)
print("[Q] quit [↑/↓] scroll")
end
local function clampTop()
local w,h = term.getSize()
local visible = h - 3
if top < 1 then top = 1 end
local maxTop = math.max(1, #items - visible + 1)
if top > maxTop then top = maxTop end
end
-- main loop
while true do
fetch()
clampTop()
draw()
-- wait up to REFRESH seconds for input; otherwise refresh again
local t = os.startTimer(REFRESH)
while true do
local e, a = os.pullEvent()
if e == "timer" and a == t then
break
elseif e == "key" then
if a == keys.q then
term.clear(); term.setCursorPos(1,1); return
elseif a == keys.up then
top = top - 1; clampTop(); draw()
elseif a == keys.down then
top = top + 1; clampTop(); draw()
end
end
end
end
Comments