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

[Solved] How do you return the number of items in a table? [closed]

Asked by 10 years ago

Like say your table might be like this,

Extreme = {2, 4, "Hi", false, "ImmenseKassing"}

and you wanted to print how many items were inside the table, which in this case, would be 5.

What would you do?

Locked by TheMyrco

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
4
Answered by
Unclear 1776 Moderation Voter
10 years ago

The method that 18cwatford described, with the #, would only work for elements that are in array order. Arrays are just tables defined explicitly with consecutive numerical indices, starting at 1.

For example, this is an array...

myArray ={2, 4, "Hi", false, "ImmenseKassing"}

On the other hand, this is a dictionary. It's similar to an array, but it has respective keys attached to each value. A key is like a map you can use to find the value you want; if you have the map, you can get the value.

myDictionary = {a = "test", b = "hi", c = "cat"}

But what happens if it's not in array format? # will return the number of elements that do follow the format... but what if we want them all, including the ones defined in dictionary format? Unfortunately, that means we will have to traverse through the entire table and count up the number ourselves.

Here's an example...

myArray ={2, 4, test = 3, false, "ImmenseKassing", wow = 4}

numberOfElements = 0
for key, value in pairs(myArray) do
    numberOfElements = numberOfElements + 1
end

print("Traversal Count :", numberOfElements) -- 6 elements
print("Count with # :", #myArray) -- 4 elements
Ad
Log in to vote
2
Answered by
User#2 0
10 years ago

You would put a # infront of it (the table or the variable the table is assigned to).

Examples:

local MyTable = {2, 4, "Hi", false, "ImmenseKassing"}
print(#MyTable) --> 5
print(#{1, "A", 6 + 12, true}) --> 4