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

What does the hashtag operator do?

Asked by
stepatron 103
6 years ago

The wiki says it says the length of the table, but I dont get it. Does it mean that it turns the string into a table like [H, e, l, l, o]? And then lists the length of it? And does it start at the number 0? Like string[0] == 'H'? Thank you

2 answers

Log in to vote
1
Answered by
Avigant 2374 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

The # is the length operator. To quote the Lua 5.1 manual:

The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

Arrays in Lua begin at 1.

It is important to note that though you can typically set the behavior of the # operator on values / data types with __len, in Lua 5.1 specifically you cannot implement the __len metatable field for tables.

Ad
Log in to vote
0
Answered by 6 years ago

The # operator returns the length of a table or string.

Example:

local words = {“Hello”, “Hi”, “Hope the reader”, “of this has a good day”}

print(#words)

The code above will print 4. As you can see, there are 4 objects inside the table.

The following example will print how many letters there are in a word, this counts spaces as well. We won’t use them, but it’s a good thing to know.

local word = “Compatible”

print(#word)

The above code will print 10. There are 10 letters in the word “Compatible”, so it will print 10.

0
this is just a tl;dr of the answer xd User#19524 175 — 6y

Answer this question