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.
Asked
Active
Viewed 114 times
1 Answers
3
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.

Jack Taylor
- 5,588
- 19
- 35
-
1That's perfect, thank you! I didn't know about such function and I think it's going to be extremely useful not only for this kind of cases but surely others... About the arbitrary order, I wouldn't have expected a different behavior (for the nature of Lua dictionaries), but it's something one may have in mind in some cases, of course. Well, thanks again for letting me know and greetings! – Rai Apr 15 '23 at 00:33