print(a.len) -- function: 0xc8a8f0
This prints a string representation of a.len
which is a function value. All strings share a common metatable.
From Lua 5.4 Reference Manual: 6.4 String Manipulation:
The string library provides all its functions inside the table string.
It also sets a metatable for strings where the __index field points to
the string table. Therefore, you can use the string functions in
object-oriented style. For instance, string.byte(s,i) can be written
as s:byte(i).
So given that a
is a string value, a.len
actually refers to string.len
For the same reason
print(a.len(a))
is equivalent to print(string.len(a))
or print(a:len())
. This time you called the function with argument a
instead of printing its string representation so you print its return value which is the length of string a
.
print(len(a))
on the other hand causes an error because you attempt to call a global nil value. len
does not exist in your script. It has never been defined and is hence nil
. Calling nil values doesn't make sense so Lua raises an error.
According to Lua 5.4 Reference Manual: 3.4.7 Length 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.)
You can also call print(#a)
to print a
's length.
The length operator was introduced in Lua 5.1,
#a
print(a.len(a))
works?