What does # mean in Lua programming?

LuaServer Side ProgrammingProgramming

The unary operator # is known as the Length operator in Lua. It is used almost everywhere in Lua. By everywhere, I meant that anywhere we would require to calculate the length of the any string or can also be used in tables also, but when it comes to table, it is generally not preferred to use the # operator as it doesn’t calculate the number of elements present inside the table.

Let’s explore different examples of the length operator to understand how we can make use of it.

Example

Consider the example shown below −

 Live Demo

print(#"abcdefg")
print(#{"a", "b", "c", 77})

Output

7
4

In the above example, the length operators work perfectly fine but when it comes to the table elements, it doesn’t work as expected.

Example

Consider the example shown below −

 Live Demo

print(#{["a"]=1, ["b"]=9})

Output

0
raja
Published on 19-Jul-2021 11:27:06
Advertisements