Make loop check whole table before returning

Problem I am having is when a player axes down a tree, I do checks and what not to make sure the axe they have is capable of taking down that specific tree, and so each axe has a ‘Strengths’ setting. This basically determines what type of tree they can cut down. However, I am having problems with it returning before checking the other items.

-- Fires when an item is hit
for _, v in pairs(Settings.Strengths) do
	if hit.Parent.Name ~= v then return end
end

-- Settings
Settings.Strengths = {'Oak', 'Birch'}

So if I go print(hit.Parent.Name) it prints ‘Oak’, so that should pass through the loop, however, if ‘v’ in the loop is == Birch then it returns, and stops there. How can I allow the loop to search through the entire table before making a judgment on whether to continue or return

2 Likes

So im guessing you want to check if the axe can chop down the tree or not? If so, then the only thing i can think of is making a bool variable (set to false), and when going through the table, if v is equal to the name, then set the bool to true.

Kind of like this:

local CanChop = false

for _,v in pairs(Settings.Strengths) do
    if hit.Parent.Name == v then
        CanChop = true
    end
end

if the bool is true, you can do whatever you want with said wood. Hope this helped!

3 Likes
if table.find(Settings.Strength, hit.Parent.Name) then
	print("deforestation time")
end
2 Likes

Why are you still iterating in the loop when you’ve already found that the ax can chop down the tree? You could just do this:

for _, v in pairs(Settings.Strengths) do
    if hit.Parent.Name == v then
        -- ax is strong enough, do stuff to chop tree down
        return
    end
end

Even better you can do what @Spooce reccomended. You don’t have to iterate through a loop, so it saves time and makes your code look neat. But, if you have some reason to use the for loop, you should just do what I reccomended.