Best Way to Check Empty Table

What would be the best way to check if this table is empty:

local Table = {}
Table[workspace.Part] = true
3 Likes
function isEmpty(t)
    local hasRecord = false
    for _,_ in pairs(t) do
        hasRecord = true
        break
    end

    return hasRecord
end

Note: You can simplify this so it just returns true in the for loop, but I opted for a more explicit approach to avoid potential confusion.

1 Like

would something like

next(Table)

work?

2 Likes

Oh, wow. I didn’t even think of that. That makes this a lot simpler:

function isEmpty(t)
    return next(t) ~= nil
end
10 Likes

I assume it would be faster than your first posted solution since it deals with roblox’s backend?

It would be somewhat faster most likely, but not because of what you mention. next is a built-in Lua function and doesn’t interact with the Roblox api. The reason why it is faster is because you have no loop setup cost and you’re doing fewer statements/comparisons.

4 Likes

Just a head up, I know that this post is old. But to clear any confusion relating with the function name, the returning should be like this:

function isEmpty(t)
    return next(t) == nil
end
16 Likes