Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to determine if a Lua table is empty (contains no entries)?

Tags:

lua

lua-table

People also ask

How does Lua tables work?

Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need. Lua uses tables in all representations including representation of packages.

Are there lists in Lua?

The Linked lists in Lua are of two kinds, namely singly-linked lists and doubly linked list. A singly linked list in Lua will have a reference pointing to the first node in a singly linked list, and there is a reference from each node to the next node in a singly linked list.

What is table insert in Lua?

The table.insert function inserts an element in a given position of an array, moving up other elements to open space. Moreover, insert increments the size of the array (using setn ). For instance, if a is the array {10, 20, 30} , after the call table.insert(a, 1, 15) a will be {15, 10, 20, 30} .


Your code is efficient but wrong. (Consider {[false]=0}.) The correct code is

if next(myTable) == nil then
   -- myTable is empty
end

For maximum efficiency you'll want to bind next to a local variable, e.g.,

...
local next = next 
...
... if next(...) ...

(When next is local, the code finds primitive function next by a constant-time indexing operation into an array of "upvalues." When next is left global, finding next involves indexing index the "environment" hash table, which contains the values of the global variables. This indexing operation is still constant-time, but it is significantly slower than the array lookup for a local variable.)


better to avoid the evaluation of __eq if overloaded.

if rawequal(next(myTable), nil) then
   -- myTable is empty
end

or

if type(next(myTable)) == "nil" then
   -- myTable is empty
end

One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil, increment the counter (the counter could live in the metatable as well) and when assigning nil, decrement the counter.

Testing for empty table would be to test the counter with 0.

Here's a pointer to metatable documentation

I do like your solution though, and I honestly can't assume that my solution is faster overall.