Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
3

What EXACTLY does the length operator do?

Asked by 1 year ago
Edited 1 year ago

Many people have been arguing with me with this kind of code:

print(#{"1", "2", "3"})

The output:

3

Now, people argue that the octothorpe (#) returns the number of values in a table, and it does. They're correct.

The other day, I met somebody who thought they could return the number of values in a DICTIONARY:

print(#["oof"])

He, of course, was wrong and got an error. But he then argued that...

print(#"oof")

...is the same as...

print(string.len("oof"))

Both lines return the number 3. However, I argued that the octothorpe works on both strings and tables, and I was right (well, duh).

The very next thing he argues about is this:

print(#{"a", [3] = "b"})

He thinks that the output is 5, because he claimed that "Since there are 2 strings and 1 number in square brackets, the output is 5." BUT, the output is actually ONE. Why? The octothorpe returns only the last bracket key for tables starting with 1. Because [3] is the only bracket value in the table, the output is 1 and not 5.

So how exactly does this work? I really want this guy to stop annoying me.

0
Non-numerical indices do not count towards the length of a table. User#24403 47 — 1y

1 answer

Log in to vote
2
Answered by
Kiriot22 3183 Moderation Voter Community Moderator
1 year ago

Let me clear it up then

1) Tables

When # is used on a table, it returns the highest numerical index it can find without stumbling upon nil.

For example

local a = {"hello", "world"}
print(#a)

will print 2, because a[3] is nil.

Another example

local a = {"hello"}
a[3] = "hi"
print(#a)

will print 1, because a[2] is nil.

Note that the # operator will not take into account any dictionairy values.

2) Strings

Yes, # works exactly the same way string.len does

Also to add to @MCAndRobloxUnited's comment, doing t[#t + 1] = val is not using addition on a table. It can be used as a substitute for table.insert. Let me explain:

local t = {"hello"} --table's length aka #t is 1
t[#t + 1] = "world" --#t + 1 is 2, so this is equal to t[2] = "world", as you can see, it inserts the value at the end of the table
0
just what i needed, thanks DeceptiveCaster 3043 — 1y
Ad

Answer this question