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?

s.epicrow.com:22003.png

Posted

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

If I help you in a thread and you need further assistance, please don't PM me - use the thread you created instead. This way everyone on the forum can take advantage of it.

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)

s.epicrow.com:22003.png

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.

If I help you in a thread and you need further assistance, please don't PM me - use the thread you created instead. This way everyone on the forum can take advantage of it.

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?

s.epicrow.com:22003.png

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