1. Yes/No Menu
First and easiest type of menu is a yes/no menu. We need it to act like:
1. Print "Yes No" with one option highlighted, like ">Yes< No" 2. Wait for key pressed. 3. If pressed enter return yes (true) or no (false) and end program 4. If pressed arrow left/right highlight the correct option and go to Step 1.
okay, here is the code:
what it does is:
2. Customizable Menu
Okay, it's now time for the more advanced stuff. Say, you don't want all your menus to only have yes/no options, right? Now I will show you how to make a better version.
1. Get the list of options, preferably a table. 2. Print those options. 3. Select the first one. 4. If pressed arrow up go one option up and go to step#2. 5. If pressed arrow down do the reverse and go to step#2. 6. If pressed enter end and return selected option.
Code:
function CUI(m)
n=1
l=#m
while true do
term.clear()
term.setCursorPos(1,2)
for i=1, l, 1 do
if i==n then print(i, " ["..m[i].."]") else print(i, " ", m[i]) end
end
print("Select a number[arrow up/arrow down]")
a, b= os.pullEventRaw()
if a == "key" then
if b==200 and n>1 then n=n-1 end
if b==208 and n<=l then n=n+1 end
if b==28 then break end
end
end
term.clear() term.setCursorPos(1,1)
return n
end
And explanation:function CUI(m) --declare function
n=1 --declare selected option
while true do --start a loop for the 'go to step#2' part
term.clear() term.setCursorPos(1,2) --clear the sceen and position the cursor
for i=1, #m, 1 do --traverse the table of options
if i==n then print(i, " ["..m[i].."]") else print(i, " ", m[i]) end --print them
end
a, b= os.pullEvent("key") --wait for keypress
if b==200 and n>1 then n=n-1 end --arrow up pressed, one option up
if b==208 and n<=l then n=n+1 end --arrow down pressed, one option down
if b==28 then break end --enter pressed, break the loop
end
term.clear() term.setCursorPos(1,1) --clear screen
return n --return the value
end
Please note that the above function requires to be called with a table, like this:
local options={
"option1",
"option2",
"option3"
}
local n=CUI(options)
print(n)
and returns the number of the option chosen.
Do you want me to make some other types of menus as well? If so, post them below.


This topic is locked










