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

lua-table contains
lua table functions
lua table next
lua array length
lua table to string
lua print table
lua-table insert
nginx lua table

What's the most efficient way to determine if a table is empty (that is, currently contains neither array-style values nor dict-style values)?

Currently, I'm using next():

if not next(myTable) then
    -- Table is empty

Is there a more efficient way?

Note: The # operator does not suffice here, as it only operates on the array-style values in the table - thus #{test=2} is indistinguishable from #{} because both return 0. Also note that checking if the table variable is nil does not suffice as I am not looking for nil values, but rather tables with 0 entries (i.e. {}).

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

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

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

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

Most efficient way to determine if a Lua table is empty (contains no , efficient way to determine if a Lua table is empty (contains no entries)? .lua. if next(myTable) == nil then. -- myTable is empty. end. Comment on gist. Sign in to​  Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself.

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.

efficient way to determine if a Lua table is empty (contains no entries)?, What's the most efficient way to determine if a table is empty (that is, currently contains neither array-style values nor dict-style values)?. Currently, I'm using  Stack Overflow Public questions and answers; How do I append to a table in Lua. Most efficient way to determine if a Lua table is empty (contains no entries)? 91.

This is probably what you wanted:

function table.empty (self)
    for _, _ in pairs(self) do
        return false
    return true

a = { }
a["hi"] = 2
a["hi"] = nil



2.5 – Tables, An associative array is an array that can be indexed not only with numbers, but also queues, and other data structures, in a simple, uniform, and efficient way. When a program has no references to a table left, Lua memory management will a = {} -- empty table -- create 1000 new entries for i=1,1000 do a[i] = i*2 end​  I have this table in lua: local values={"a", "b", "c"} is there a way to return the index of the table if a variable equals one the table entries? say . local onevalue = "a" how can I get the index of "a" or onevalue in the table without iterating all values?

better to avoid the evaluation of __eq if overloaded.

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


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

Lua table functions, Lua table functions Since keys and values can be any data type (except nil) it follows that tables can contain other tables. If the table has "holes" in it - that is, numeric keys with gaps in the sequence If you want to know if a table is empty, or not, you can test: [Best viewed with any browser - 2K] [Hosted at FutureQuest​] Since Tables in Lua are as much like arrays than anything else (even in a list context), there is no real correct way to append one table to another. The closest concept is merging of tables. Please see the post, " Lua - merge tables? " for help in that regard.

try serpent, work for me

serpent = require 'serpent'

function vtext(value)
  return serpent.block(value, {comment=false})

myTable = {}

if type(myTable) == 'table' and vtext(myTable) == '{}' then
   -- myTable is empty

Lua Unofficial FAQ (uFAQ), 1.17 What is the difference between a.f(x) and a:f(x)?; 1.18 How are variables scoped? 7.2 How would I save a Lua table or a function for later use? Functions are first-class values and may be anonymous, so that functional styles can be The easiest is to check dynamically whether a given global variable has been  I have a table of objects, and a user can choose an object in the table at any given order in the table and place it in another slot in the table. When that happens I need the table to shift from the selected dropped slot and fill the empty slot.

Hash table, In computing, a hash table (hash map) is a data structure that implements an associative array In many situations, hash tables turn out to be on average more efficient than a perfect hash function can be used to create a perfect hash table that has no collisions. In each lookup or delete operation, check both tables. Lua tables can be used to create any Abstract Data Structure, in your case you indicated that you want a "list". A Lua table is a data structure that combines numeric index based access with key:value access. Based on your example, you are using the numeric index feature of tables that let you iterate (with ipairs()) through those values.

lua script, Jump to Best Answer Hi all, I have a lua script that pulls back hubs, robots, probes and the I am unsure what could be causing this and also how to add error initially empty list of hubs (table meant to hold the full list of robots and probes) determine if created value is valid or not, and parse it if so if your DB stores table data in B-trees you can do it this way and have the benefit, that you have already selected the data you might need. if you have i.e. ORACLE without index-organized tables and do NOT need the data but. just the confirmation, that a record exists, select only_key_fields from tab where x=y

Tables are the main (in fact, the only) data structuring mechanism in Lua, and a powerful one. We use tables to represent ordinary arrays, symbol tables, sets, records, queues, and other data structures, in a simple, uniform, and efficient way. Lua uses tables to represent packages as well.

  • Good point on the technical correctness; in the particular cases I've been utilizing the original code, false wouldn't be an expected key so the if not worked fine, but I'll probably make a habit of comparing to nil instead in the future, just as a good habit. And yes, I've been binding common utility functions to local vars for speed. Thanks for the input though.
  • I find it hard to agree with wrongness when the code works as intended
  • Why do we gain speed by doing local next?
  • @Moberg This is due to how LUA handles its namespace. The very dumbed down version, is it will first climb up the local tables, so if there is a local next in the current block, it will use that, then climb up to the next block, and repeat. Once out of locals, it will only then use the Global Namespace. This is a dumbed down version of it, but in the end, it definitely means the difference in regards to program speed.
  • @Moberg the less dumbed down version, in the context of lua 5.2 & 5.3, is that non locals are either upvals or _ENV lookups. An upval has to go through an extra layer of indirection, whereas an _ENV lookup is a table lookup. Whereas a local is a register in the VM
  • The original question is not about counting just "array" entries.
  • 0x6's suggestion isn't specific to array-style entries (newindex works for both numerical and non-numerical indices). However, the main issue would be detecting when nil is assigned, since __newindex does not trigger if the key already exists in the table.
  • For this trick to work, the metatable would have to implement both __index and __newindex, storing the actual data in a shadow table and keeping the real table empty so that __index will be invoked at all. Thinking out loud, I suspect that the raised cost of every single lookup can't be worth it.
  • next() is more efficient (and more concise) than looping over pairs().
  • In fact, looping over pairs() is essentially just using the next() technique, but with more overhead.
  • Also, writing into the standard table library is not recommended.
  • I'm a Lua noob trying to understand why this answer was down voted. I'm guessing it is because in Lua, "if two objects have different metamethods, the equality operation results in false, without even calling any metamethod". (The quote is at the bottom of this page from Programming in Lua on ). Does that remove the need to avoid __eq overloading for nil?
  • That's not the question.
  • This won't work on a table that as strings as index's