Detecting if table is empty (dictionary)

When I do a print(slotContents) I get ‘{}’ returned on empty tables, but can’t do

if slotContents == {} then

As that doesn’t seem to work

for slotNumber, slotContents in ipairs(PlayersData.Inventory) do
			if slotContents == {} then -- Empty slot
				print("EMPTY") -- NEVER PRINTS
				slotContents.Id = BlockId.Value
				slotContents.Quantity = 1
				
				ChangedSlot = slotNumber
			end
		end

When I print PlayersData.Inventory this is what I get:

[1] = :arrow_forward: {…},
[2] = {},
[3] = {},
[4] = :arrow_forward: {…},
[5] = {},
[6] = {},
[7] = :arrow_forward: {…},
[8] = :arrow_forward: {…},
[9] = {}

So I want to be able to tell if a slot has an empty table, however if I do #slotContents, I always get 0, as the stuff inside the table is aranged as a dictionary, and thus using # won’t retrieve the amount of stuff.

[1] for example

[1] =  ▼  {
     ["Id"] = "2",
     ["Quantity"] = 12
                    },

try this

if #slotContents == 0 then

the hashtag basically returns the amount of things in a table

Please read the question before giving me an uneducated answer :upside_down_face:

3 Likes

oh sorry i just read the first lines and i thought that will be the solution

idk try this perhaps it will work

local empty = true
for i,v in pairs(slotContents) do
    empty = false
end
if empty == true then
    idk

not sure but i think if the table will be nil the for i,v loop wont fire and empty will stay true

1 Like

Here is a function to do that

local function IsEmpty(tbl)
	return (next(tbl) == nil)
end

From this other post but I believe EchoReaper had a typo error it should be == nil because if it’s empty next returns nothing.

Edit: Checkout these sources for more utility functions:
AeroGameFramework TableUtil
Libaries++ has is empty as well.
NevermoreEngine? can’t find it.

20 Likes

Use pairs() if PlayerData.Inventory is a dictionary.

pairs() and ipairs () are functions that can be used with a for loop to go through each element of an array or dictionary without needing to set starting or ending points.
pairs() is used with dictionaries, and ipairs() is used with arrays.

Anyways, to the solution:

if next(Table) == nil then
   -- Table is empty.
end
4 Likes

I use ipairs because I want to go in numerical order. If I do pairs, it will just grab the contents at random. ipairs goes 1, 2, 3, 4, etc.

You can use table.sort, to sort lowest to highest.
Here’s a module I made that does this:

local SortModule = {}


function SortModule:HighToLow(Table)
	table.sort(Table, function(a, b)
		return (
			a > b
		)
	end)
end

function SortModule:LowToHigh(Table)
	table.sort(Table, function(a, b)
		return (
			a < b
		)
	end)
end


return SortModule