Easy way to detect if there's more than limit of the same value in table

Hi, today i wan’t to show you easy way how to see if there is more than limit of same values in table, let’s start.

1. Making your own table

local t1 = {"Forest","Desert","Ice","Ice"}
local max = 1 -- only one biome of same type can be here

for this i made biomes list that has been choosen

2. Writing function

local function Check(array)
	table.sort(array) -- we have to sort table
	
end

now we made function that sorts gived table, but it’s not the end. We have to look if next value is the same as current

3. Loop

local index = 0
for i,v in array do
if array[i+1] == v then
index+=1

else

index = 0
end
end

Ok, now we have a working loop that gives us how many elements of the same type in table, and set it to 0 if the next element is different or it’s nill
remember that we have to put our function to determine limit before the next element shows! otherwise this will not detect anything

4. Checking if limit reached

if index >= max then
-- code, i made element will be removed
table.remove(array,i) -- you can put anything
index = 0 -- remember to reset!

end

Now we have basic detector!

For table.remove(), this will remove current index, soo next index will do the same, and then repeat the same process

If you wan’t more tutorials, like it and leave a comment, good luck with scripting :}

Note: you can use module script to improve this script, i’ll make another tutorial about tables later

3 Likes