As summary states... Lets say I want to quickly know if a table is empty or has been filled with some hash entries, is there a simpler and generic (I mean, not having to resort to check if certain entry exists) way than having to parse the table to simply know this? Thanks.
Yes, you can use the next function to do this. If the table t
is empty, then next(t)
will return nil. Otherwise, next(t)
will return the first index and the associated value.
local t1 = {}
local index1, value1 = next(t1)
print(index1, value1) -- nil nil
local t2 = {a = "b", c = "d"}
local index2, value2 = next(t2)
print(index2, value2) -- c d
Note that the order that next(t)
accesses the table in is arbitrary. In the case of t2
, it happened to choose index "c" first.