Huh. Actually now that I've looked around in the tutorials section, I'm not seeing anything that's very simple to follow while at the same time making use of good coding habits. I myself have made a tutorial on menus, but it's more for intermediate-advanced Lua programmers than for those new to programming.
Anyway, here's how I would go about it (note - please read the comments and don't just copy/paste! :)/>)
local termX, termY = term.getSize() --Get the terminal size
local function centerPrint(text, y) --Pretty self explanatory: just writes text to the center of the screen
term.setCursorPos(termX/2-#text/2, y)
term.write(text)
end
local menu_options = { --Our menu options: you can increase or decrease this list as you wish
[1] = "menu option 1";
[2] = "menu option 2";
[3] = "menu option 3";
}
term.clear() --Just clear the screen first
local startY = termY/2-#menu_options/2 --This is the starting position that we'll draw at.
for i=1, #menu_options do --A for loop which will write our menu options to the screen.
centerPrint("["..i.."] "..menu_options[i], startY)
startY = startY + 1
end
term.setCursorPos(1, termY)
term.write("Press a number to select the menu option...")
local selected = false --This will be our selected menu item, but since nothing has been selected yet we''ll just set it to false
while true do
local e = {os.pullEvent()} --This will take events and put them into an event table
if e[1] == "char" then --If the returned event is a character then
if menu_options[tonumber(e[2])] then --Check if the pressed key is inside of the menu_options table
selected = tonumber(e[2]) --If so, set selected to the index and break out of our loop
break
end
end
end
print("You've selected: ".. menu_options[selected])
In case you're confused by anything in this tutorial, here's a small list of the important stuff:
- Tables - signified by brackets { }, this contains a number of items that correlate to the given index.
- tonumber(e[2]) - This simply converts the event returned by os.pullEvent() into a number, if it is one. If it is not a number, it will return a nil value (essentially nothing)
- term.setCursorPos(termX/2-#text/2, y) - This divides the length of the terminal in half, and then subtracts the length of the text/2 from that so we can center the text nicely
And that's about it. If you've got any more questions, feel free to ask.