57

I have seen the hash character '#' being added to the front of variables a lot in Lua.

What does it do?

EXAMPLE

-- sort AIs in currentlevel
table.sort(level.ais, function(a,b) return a.y < b.y end)
local curAIIndex = 1
local maxAIIndex = #level.ais
for i = 1,#currentLevel+maxAIIndex do
    if level.ais[curAIIndex].y+sprites.monster:getHeight() < currentLevel[i].lowerY then
        table.insert(currentLevel, i, level.ais[curAIIndex])
        curAIIndex = curAIIndex + 1
        if curAIIndex > maxAIIndex then
            break
        end
    end
end

Apologies if this has already been asked, I've searched around on the internet a lot but I haven't seem to have found an answer. Thanks in advance!

Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
Bicentric
  • 1,263
  • 3
  • 12
  • 12

3 Answers3

73

That is the length operator:

The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).

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).

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • any reason why i would get a syntax error `unexpected symbol near `#'` then? This is somebody else's code that nobody else seems to have problems with... – Michael Apr 07 '20 at 02:32
6

# is the lua length operator which works on strings or on table arrays

Examples:

print(#"abcdef")  -- Prints 6
print(#{"a", "b", "c", 88})  -- Prints 4

-- Counting table elements is not suppoerted:
print(#{["a"]=1, ["b"]=9}) -- # Prints 0
Mercury
  • 7,430
  • 3
  • 42
  • 54
2

#is most often used to get the range of a table. For example:

local users = {"Grace", "Peter", "Alice"}
local num_users = #users

print("There is a total of ".. num_users)

Output: 3