Jump to content

Check if index value exists


Drakath

Recommended Posts

Posted

Is there a way to check if a specific index value in a table exists?

For example I have two tables:

table = {{1,2},{1}}

Script selects a random table.

How can I check if table[randomTable][2] exists?

Posted
Well, if it doesn't exist - it should return nil.

I did try those:

if table[2][2] then 
if table[2][2]~=nil then 

but in both cases it's: ERROR: attempt to index field '?' (a nil value)

Posted

Well, because that value evidently doesn't exist. Hence, it returns nil.

If you'd have done it like this instead;

table[1][2] 

Then it would return 2.

table[2][1] 

Would return the last value, 1.

Posted

(Just seen Dealman's latter reply but still going to publish this as an additional information).

As Dealman stated above, in case an index does not contain anything it returns nil. Which entails an error when indexing a nil value.

  
local table = 
{ 
    {"A", "B"} 
    {"A"} 
} 
if table[2] then 
    print(tostring(table[2][2])) -- tostring in order to be able to print any kind of variable 
    print(tostring(nil)) -- prints nil 
end 
if table[3] then -- does not exist, hence not following up 
end 
  

Posted
  
not table[2][2] -- not + nil = true / false + false = true / negative + negative = positive (mathematical reference) 
  

So you can basically go through an if statement, or any other way you prefer, using the above trick to check whether that table value is either nil or false - as I did with table[3] within my previous sample code.

Posted
  
not table[2][2] -- not + nil = true / false + false = true / negative + negative = positive (mathematical reference) 
  

So you can basically go through an if statement, or any other way you prefer, using the above trick to check whether that table value is either nil or false - as I did with table[3] within my previous sample code.

What if table[randomIndex][2] can be either nil or true?

  
local isTrue = not table[randomIndex][2] --if true it will convert to false 
if not isTrue then --if not false = true? 
  

Is that how it works?

Posted

Check the index at each level, everything that has a value is true while false and nil (no value) means false in below if statement.

if not table or not table[randomIndex] or not table[randomIndex][2] then return end 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...