I have just started delving into Lua, and I learnt that C++ object properties could be accessible through metatables.
I am trying to access such an object's functions in a game's script: "GameLib". It is available in Lua as a global variable, but getmetatable() returns nil:
-- example usage elsewhere in the scripts:
local pPlayer = GameLib.GetLocalPlayer();
-- my tried code:
local mt = getmetatable(GameLib);
print("Metatable type:" .. type(mt)); -- "Metatable type: nil"
What could be the problem? Are there cases, when a C++ object has no metatable? If so, is there another way to access its properties?
From the Lua 5.4 Reference Manual:
2.4 Metatables and Metamethods:
Every value in Lua can have a metatable.
By default, a value has no metatable, but the string library sets a metatable for the string type
So there are cases where values, even userdata have no metatable. In fact that's default.
6.1 Basic Functions: getmetatable
If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object.
So the that leaves us with two options why getmetatable(GameLib)
returns nil
:
GameLib
does not have a metatablegetmetatable
is not Lua's getmetatable
. It has been overwritten by a function that returns nil for at least some values. Trivial function getmetatable() end