Jump to content

How can I check: "is table empty"?


Flaker

Recommended Posts

How can I check: "is table empty"?
if table == nil then 
print("table is empty") 
end 
  

It's wrong! You check if variable is nil.

:/

I written this function

  
function table.empty( a ) 
    if type( a ) ~= "table" then 
        return false 
    end 
     
    return not next( a ) 
end 
  

Link to comment

If it's an ipairs (the most common form) table, you can simply use

#tableName 

and it will return how many items are in the table.

If it's a pairs, you can use

tableCount = 0 for k, v in pairs(tableName) do tableCount = tableCount+1 end 

Link to comment
If it's an ipairs (the most common form) table, you can simply use
#tableName 

Wrong.

Example

print( 'empty = ' .. tostring( #{ [0] = 'a' } == 0 ) ) -- empty = true 

Operator # used ipairs method for calculate!

ipairs loop only numeric indexes ( from 1 index ) and only in order.

Use my function.

  
function table.empty( a ) 
    if type( a ) ~= "table" then 
        return false 
    end 
     
    return not next( a ) 
end 

Example

  
print( 'empty = ' .. tostring( table.empty { [0] = 1 } ) ) -- false 
print( 'empty = ' .. tostring( table.empty { [10] = 10, [2] = 2 } ) ) -- false 
print( 'empty = ' .. tostring( table.empty { } ) ) -- true 
  

Added to useful functions.

https://wiki.multitheftauto.com/wiki/Table.empty

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