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

What does # do?

Asked by
emite1000 335 Moderation Voter
10 years ago

Title says it all. What does the pound symbol do when you use it in LUA scripting?

2 answers

Log in to vote
2
Answered by
Ripull 45
10 years ago

The number operator (#) returns the number of elements in a list (aka. table).

list = {"hello", 1, true};

print(#list);

--> 3
0
Your answer was simpler and easier to understand. emite1000 335 — 10y
0
Taslem's answer was more informative though which is more beneficial than a simple answer. Ekkoh 635 — 10y
Ad
Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

The # unary operator refers to table length (the number of things in a table being used as a list). Using it looks like this:

#list

(It is a unary operator, so syntactically it acts the same way that unary minus (negation) does, e.g., just like -x)


It counts the number of indices in a table starting at 1 until it finds a nil.

E.g., these are the lengths of the following tables:

print( #{1,3,5,-5,7} );
-- 5

print(
    #{
        [1] = 5,
        [2]=4,
        [4]=9
    }
);
-- 2, since index 3 is nil

print(
    #{
        1,
        5,
        cat=three,
        false,
        [4] = true,
        [0] = 2,
        [6] = 99
    }
);
-- 4; Counting indices 1, 2, [3] is false; [4] is true.
-- 'cat' and '0' are not indices counted by table length;
-- [6] is not counted since there is no 5

print(
    #{
        1,
        nil,
        2,
        nil,
        3
    }
);
-- Length is 1, since value at [2] is `nil`.

Answer this question