Jump to content

Check if index value exists


Drakath

Recommended Posts

(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 
  

Link to comment
  
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.

Link to comment
  
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?

Link to comment

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...