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:
Create a variable called index
Loop through the table
Inside the loop, I add the index by 1.
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
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