Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does this function not return true/false?

Asked by 9 years ago

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

Log in to vote
1
Answered by
Tkdriverx 514 Moderation Voter
9 years ago

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
0
Incorrect. The table will actually return the 'false' condition. DigitalVeer 1473 — 9y
0
Yeah, I just moved the 'return false' portion to an 'else' function to fix that problem. Wafflehagen 20 — 9y
0
The return false is actually unnecessary, since without it the table would return nil, which is a 'falsy' value. Perci1 4988 — 9y
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. Tkdriverx 514 — 9y
Ad
Log in to vote
1
Answered by 9 years ago

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

Answer this question