Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I havw table with 2 tables(with names). Why prints 0?

I have table.

local foodList = {
	["Apple"] = {"rbxassetid://923453681", "rbxassetid://923453682", Vector3.new(1,1,1)},
	["Pineaple"] = {"rbxassetid://677816839", "rbxassetid://677816891", Vector3.new(1,2,1)},
}
print(#foodList)

-- Will be 0, not 2

Why not 2?

2 answers

✓ Accepted answer

The problem here is that they have names. #table will return the amount of elements when they don't have names, such as
local foodList = {"Apple","Banana"}
However, in your situation you are using an array with names. A quick work around for that is to make a function that returns the amount of elements in an array.

function tableSize(input)
    local size = 0
    for i,v in pairs(input) do
        size = size + 1
    end
    return size
end

local foodList = {["Apple"] ={"rbxassetid://923453681","rbxassetid://923453682", "fsa"},["Pineaple"] = {"rbxassetid://677816839", "rbxassetid://677816891","fsa"}}

print(#foodList)
print(tableSize(foodList))

Output:

0
2

If you need anymore help just ask! :D

1 comment

0

Oooooh. Thank you for useful information!

Basically Lua is really dumb, so rather than make # mean "size" like any normal human being capable of any modicum of rational thought would expect, it only deals with integer indices starting from 1.

function dictionaryCount(d)
    count = 0
    for key, value in pairs(d) do
        count = count + 1
    end
    return count
end

That should do what you want.

However, bare in mind that while the execution of # is basically free, and doesn't change no matter how large the table, the execution of dictionaryCount scales linearly with how many things are in the table.

If you're familiar with big-O notation, dictionaryCount(d) is O(n)

1 comment

0

I wanted to use "for do" for this, but I thought it wouldn't work. Thanks for explaining.

This discussion is preserved as it was. New answers, comments, and votes are closed.