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

Right click menu

Started by ChiknNuggets, 03 January 2013 - 06:22 PM
ChiknNuggets #1
Posted 03 January 2013 - 07:22 PM
well i kinda want to right click on an icon and then it comes up with a right click menu and so far i got this


elseif event == "mouse_click" and p1 == 2 then
local x = p2;y = p3

i need a way to make the menu in a way that i dont need to have the sprite premade i just want to have it all code cant think of an easy way though


any sugestions
Kingdaro #2
Posted 03 January 2013 - 09:38 PM
I did something like this a while ago with an OS project thing I had. It was basically a function that you would use, and it'd "halt" the entire program and wait for a click, then return whatever option the user clicked, or nil if he clicked out of the menu.

So this function could just be called "popupMenu". The first two arguments would be the x and y positions of the rightclick menu, and you can feed it mouse coordinates from whatever loop runs your program. You could then give it the option to take variable arguments as menu options.

My logic here is that I'm going through the menu options, or the "args", and making an "object" for each one. Objects are really just tables with various values that makes mouse position checks easier. Every object is positioned under one another and dependent on the x and y values given to the function. Then just go ahead and draw all of the "objects", or menu options.

After that, we get a mouse click from the user, then check it against all of the menu options to see if the mouse x and y is within the area of that option. If it is, return the text of that object.

This is what that function would look like:

function popupMenu(x, y, ...)
	local args = {...}
	local objects = {}
	for i,v in pairs(args) do
		objects[i] = {
			x = x;
			y = i + y - 1;
			text = v;
		}
	end
	for _, option in pairs(objects) do
		term.setCursorPos(option.x, option.y)
		term.write(option.text)
	end
	local _, button, mx, my = os.pullEvent('mouse_click')
	for _, option in pairs(objects) do
		if mx >= option.x and mx < option.x + #option.text
		and my == option.y then
			return option.text
		end
	end
end

Here's an example of how to use it:

local input = popupMenu(2,2, 'Bacon', 'No Bacon')
if input == 'Bacon' then
  print 'yay!'
elseif input == 'No Bacon' then
  print 'ffs.'
end

This code makes a menu at position 2, 2, with the options "Bacon" and "No Bacon".
tesla1889 #3
Posted 03 January 2013 - 09:39 PM
probably the easiest way to do this is a 2d table

if pos[x][y] then
<do stuff>
end
ChiknNuggets #4
Posted 03 January 2013 - 09:50 PM
Made like 2 modifications to fit mine nicely, thank you so much exactly what i needed, the way i was thinking of doing this was ridiculously longer