What is the difference between the “#” operator and string.len(s) function?

Basically, they are identical when used on Lua strings; however, the # operator will also return the length of an array as long as that array does not contain any “holes”. Similarly, while the operator can be used on arbitrary tables, the value it returns is based on numeric indices (so it may not give you the result you expect). For further discussion of this, see Section 2.5.5 of the Lua 5.1 Reference Manual.

  • The “#” operator is equivalent to string.len() when used on strings.
  • The “#” operator will also return the length of a table. Previous to Lua 5.1 you needed to use table.getn().

We recommend using the # operator instead of string.len() as it is more concise.

Example:

local s = 'abcd'
trace(#s, s:len(), string.len(s), s.len(s))

Trap for C/C++ programmers – embedded zeros in Lua strings:

Unlike C/C++ and other languages embedded zeros are just characters with no special significance. In C/C++ and some other languages it is used as a string terminator. An “embedded zero” is a byte with the value 0 (zero).

This means that embedded zeros are counted in the length of a Lua string. So the length of this string “a�00bc�00” (or “a�0bc�0” or “a�bc�”) would be five.

Note: a Lua escape character includes up to 3 characters therefore “�00” = “�0” = “�00”.

This means that you can load arbitrary bytes into a Lua string (image, audio, video, native code, etc.) and you do not risk having it truncated at the first ‘�’ by some library function (which could happen in C/C++ etc if you use string-related functions).

For more Information: