How to check if a number is inside a table?

How would I check if a number is inside a table, and if it is, do what the script is supposed to do?

local possibleNumbers = {1,2,3,4,5,6,7,8,9}

if table.find(possibleNumbers) then
    print('number was found inside table')
end

Any help is appreciated, thanks

You can check if a specific number is there, but there doesn’t seem to be a direct way of checking if a value of any type in general is there other than iterating over it.

local hasNumber = false

for _, value in ipairs(possibleNumbers) do
    if typeof(value) == "number" then
        hasNumber = true
        break
    end
end

if hasNumber then
    print("number was found inside table")
end
2 Likes

You can use table.find to do this. You just forgot to supply the second argument.

local possibleNumbers = {1,2,3,4,5,6,7,8,9}

if table.find(possibleNumbers, 5) then
    print('number was found inside table')
end

And that should print.

That wasn’t my goal, hence the reason I left the second argument blank. I wanted the script to check if a number entered by a player in a TextBox is inside the table, I wasn’t looking for one specific number.

I was just showing an example that it can be done. If you want to check a number from a textbox, then you would do

if table.find(possibleNumbers, tonumber(Textbox.Text)) then
     -- stuff
end

Thanks for the help, though I already figured that out through incapaz’s response

Np :slight_smile: I was showing an alternative method for other people in case they come across this post. Using built in methods are most probably faster than rewriting the same code by hand, as they use the internal engine’s C++ for doing the same thing that you write in Lua. Although in this case it’s probably so miniscule that it doesn’t matter. They’re also just faster to script with.

1 Like