Question

In Lua how would one pop/remove the next item (any order) in a key-value-pair table?

Is this possible without having to iterate using pairs?

Was it helpful?

Solution

There is a primitive function next, you can call next(t,k), where k is a key of the table t, returns a next key in the table, in an arbitrary order, and the value associated with this key.

If k is nil, next(t,k) returns the first element if there is one. So you can iterate the table from calling next(t,nil) and end when the next key is nil.

This is an simple example to demonstrate the use of next:

local t = {a = "va", b = "vb", c = "vc"}

local k,v = next(t,nil)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)

Output:

a       va
c       vc
b       vb
nil     nil

OTHER TIPS

The global function next is useful here. The docs explain it pretty well in general. To use it iteratively, this is 'key':

You may ... modify existing fields. In particular, you may clear existing fields.

A simple pop function:

 -- removes and returns an arbitrary key-value pair from a table, otherwise nil
 local pop = function (t)
    local key, value = next(t)
    if key ~= nil then
        t[key] = nil
    end
    return key, value
end

Demo:

local test = { "one", c = "see", "two", a = "ayy", b = "bee", "three" }
assert(next(test), "Table was expected to be non-empty")

local key, value = pop(test)
while key do
   print(key, value)
   key, value = pop(test)
end

assert(not next(test), "Table was expected to be empty")

If you run the demo multiple times, you might see the arbitrariness of the table sequence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top