Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by
Shaehl -11
5 years ago

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

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

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

0
Oooooh. Thank you for useful information! Shaehl -11 — 5y
Ad
Log in to vote
0
Answered by
fredfishy 833 Moderation Voter
5 years ago
Edited 5 years ago

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)

0
I wanted to use "for do" for this, but I thought it wouldn't work. Thanks for explaining. Shaehl -11 — 5y

Answer this question