Why could not aquire the metatable for the types of LUA_TNUMBER and LUA_TBOOLEAN?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Why could not aquire the metatable for the types of LUA_TNUMBER and LUA_TBOOLEAN?

孙世龙 sunshilong
As per the document(
https://www.lua.org/manual/5.3/manual.html#2.4),
which says that[emphasis mine]:
Tables and full userdata have individual metatables (although
multiple tables and userdata can share their metatables).
Values of all other types share one single metatable per type;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
that is,there is one single metatable for all numbers, one for
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
all strings, etc. By default, a value has no metatable, but the
string library sets a metatable for the string type (see §6.4).

The document clearly states that there is a one single metatable
for all numbers, for all booleans and etc.
Why could not aquire the metatable for the types of LUA_TNUMBER
and LUA_TBOOLEAN(for details, see the test below)?


Here is the aforementioned test which is done on vanilla Lua:
@localhost:~$ lua
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> int=1
> double=3.14
> type(int)
number
> type(double)
number
> getmetatable(int)
nil
> getmetatable(double)
nil
> flag=true
> type(flag)
boolean
> getmetatable(flag)
nil
> str=""
> type(str)
string
> getmetatable(str)
table: 0x144ba70
> getmetatable(str).__index
table: 0x144b350
> string
table: 0x144b350
> getmetatable(str).__index == string
true

You see "getmetatable("").__index == string" returns
ture whereas "getmetatable(3.14)" returns nil.
Reply | Threaded
Open this post in threaded view
|

Re: Why could not aquire the metatable for the types of LUA_TNUMBER and LUA_TBOOLEAN?

Dmitry Meyer
On 30/01/2021 09:27, 孙世龙 sunshilong wrote:
 > By default, a value has no metatable, but the
 > string library sets a metatable for the string type

It clearly says that only the string type has a metatable _by default_
as it is set by the standard library, but it is possible to set
metatables for numbers, booleans, etc.
Reply | Threaded
Open this post in threaded view
|

Re: Why could not aquire the metatable for the types of LUA_TNUMBER and LUA_TBOOLEAN?

孙世龙 sunshilong
In reply to this post by 孙世龙 sunshilong
>that is,there is one single metatable for all numbers.
Sorry for my poor English, I paid too much attention to this sentence
and ignore the later one in the document.
I fully understand it now. Thank you.

On Sat, Jan 30, 2021 at 3:21 PM Dmitry Meyer <[hidden email]> wrote:
>
> On 30/01/2021 09:27, 孙世龙 sunshilong wrote:
> > By default, a value has no metatable, but the
> > string library sets a metatable for the string type
>
> It clearly says that only the string type has a metatable _by default_
> as it is set by the standard library, but it is possible to set
> metatables for numbers, booleans, etc.