Grid Combination Help

Howdy. I was attempting a grid inventory system and was wondering if anyone could help me clean up the terrible “bad combination check”. Unfortunately I need it to stop the following from happening in the last video. What could I do to make this more efficient?

function autoFind(position,toolType)
	local number = tonumber(position)
	local combination = {
	for index,combo in combination do
		local bad1 = (number == 4 and combo == number+1)
		local bad2 = (number == 8 and combo == number+1)
		local bad3 = (number == 5 and combo == number-1)
		local bad4 = (number == 9 and combo == number-1)
		if bad1 or bad2 or bad3 or bad4 then
			warn('bad combination')
				backpackPanel:FindFirstChild(combo),, 0.832349, 0.473213)

With noob checks “I want a better method”

Without noob checks “Needs to work properly”

First, make a variable for the row length, just to avoid having a “magic number” in multiple places in your code.
rowLength = 4

For any given row you know which index it starts and ends at:
row 1: 1 through 4
row 2: 5 through 8

You can calculate this for each row:

rowMin = (row - 1) * rowLength + 1
rowMax = row * rowLength

You can now use these in a single check instead of manually writing four different possible bad cases. For the left and right sides of the pattern, if the index is outside rowMin and rowMax, ignore it. For the top and bottom parts its simpler, just ignore it if the row is less than one or greater than the number of rows.

Unfortunately I don’t understand how to implement this into my code. What is “row” suppose to be?

The row of the item you’re clicking on.

I don’t have anything defining the rows. They’re just frames named 1-12.
Screen Shot 2022-12-18 at 4.54.47 PM

Are the tiles always arranged in the shape you’ve shown?

Yes, they’re always in that order.

Then the row is the frame number divided by 4, plus one. (since Lua counts from one and not zero)