Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does this function not return true/false?

I just want to be able to use this function to return a true or false value. Here is the code:

local inRadius={}

function checkTable(action)
	for i=1,#inRadius do
		wait()
		print(inRadius[i])
		if action==inRadius[i] then
			return true
		else
			return false
		end
	end
end

2 answers

✓ Accepted answer

If the table is empty, it won't return anything, because it's not even searching anything.

local inRadius={}

function checkTable(action)
    for i, v in pairs(inRadius) do
        wait()
        print(v)
        if action==v then
            return true
        end
    end
    return false -- if the table is empty, then it won't return anything. So we need to add the 'return false' after it goes through the table. This is basically an "if all else fails, return this"
end

4 comments

0

Incorrect. The table will actually return the 'false' condition.

0

Yeah, I just moved the 'return false' portion to an 'else' function to fix that problem.

0

The return false is actually unnecessary, since without it the table would return nil, which is a 'falsy' value.

0

If you do an else return false, then it will return false on the first one if it doesn't match instead of searching the entire table.

Your code actually returns false if inRadius is empty, due to the fact that inRadius[i] would then be equivalent to nil, thus going to the 'false' return statement.

For proof, you can test your code with Lua's conditional ternary operator:

print(checkTable("s") and "yes" or "no")
--//No

There are a couple of issues with your code and let me point them out to you:

1.) If the table is empty, then your code will return false

2.) Your code only returns if the ***FIRST ***value in the table is homogeneous to action, and not every value.

3.) What this means is, is that if the first value in inRadius isn't action, then you are going to get it returned false, even if the proper action is in your table.

To fix this, we can simply return conditions after iteration:

local inRadius = {}

function checkTable(action)
	for _,v in pairs(inRadius) do
		if action==v then
			return true
		end
	end
	return false
end

print(checkTable("s") and "yes" or "no") --For Testing

This discussion is preserved as it was. New answers, comments, and votes are closed.