Lua Programming/length operator

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Length operator[edit | edit source]

The unary # symbol is used to obtain the length of a string or table. The length operator returns the number of bytes for strings. The length operator returns the last numeric key whose value is not nil for tables starting from 1. The length operator returns zero for tables when the first numeric key is nil or there are no numeric keys.

print (#"oranges")        -- 7
print (#{"a","b","c"})    -- 3
print (#{"a", [3] = "b"}) -- 1
print (#{a = "a"})        -- 0

Note that the string library provides the string.len function, which can also be used to determine the length of a string:

print (string.len("oranges")) -- 7