Some weird assert() Issue

Hi, So I made this simple function to get if a Value is greater than 0 or if it has a value or not, If it does not, It will error, if it does, it will continue, But I’m confused as to why it doesn’t work, Instead of continuing, it errors which I don’t understand why It’s doing so, here is the code:

local CurrentData

function CheckData(Data: {}) 
    assert(#Data > 0, "Data cannot be given no values.")
    CurrentData = Data
end
CheckData(
    {
        ["Example"] = "hello"
    }
) -- I get an Error?

What could I be doing wrong here?

Edit:

I tried printing the number of items in the Table, It gives me 0 insteaad of 1

I don’t think you can check it like that. Arrays and dictionaries are different.
An Array example:

local array = {
    "hello",
    "world",
}

print(#array) -- prints 2 as they have indexes as number.

A dictionary example:

local dictionary = {
    ["Hello"] = "world",
}

print(#dictionary) -- doesnt print a number as the indexes aren't number, or in other words, it isn't an array.

For dictionaries, I create a function called getTableLength and do the following steps:

  1. Create a variable called index
  2. Loop through the table
  3. Inside the loop, I add the index by 1.
  4. Outside the loop, I return the index.
local function getTableLength(tab: {})
    local index = 0 -- step 1

    for _, _ in pairs(tab) do -- step 2
        index += 1 -- step 3
    end

    return index -- step 4
end

Finally, you can do this for your code:

local CurrentData

function CheckData(Data: {})
    assert(getTableLength(Data) > 0, "Data cannot be given no values.")
    CurrentData = Data
end

I simplified the code but thanks, it works:

function CheckData(Data: {}) 
	local num
	for i in Data do num = i end
	assert(num > 0, "Data connot be given no values.")
	CurrentData = Data
	print"worked"
end

You can check if a table has any values with next() so you don’t have to loop through the entire thing :slight_smile:

assert(next(Data) ~= nil, "Data cannot be given no values.")
2 Likes

Thank you, I’ll keep this in mind :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.