1
votes

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?

1
Function getmetatable might be redefined to deliberately hide metatables from you (except metatables created by you). - Egor Skriptunoff
Are you sure GameLib isn't just a regular old table? What game are you using Lua in? - Joseph Sible-Reinstate Monica
@EgorSkriptunoff How common is that, compared to just using __metatable (which won't let you return a nil)? - Joseph Sible-Reinstate Monica
@JosephSible-ReinstateMonica You are right, it was indeed a table, where function names are the keys and - mostly - the C++ pointers are the entries. I didn't know that functions can be called directly without indexing or anything like that. Thanks for the answers! - Zsolt DOKA
@JosephSible-ReinstateMonica - Sometimes it is easier to redefine one function than insert additional field into 50 metatables. - Egor Skriptunoff

1 Answers

2
votes

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:

  1. GameLib does not have a metatable
  2. getmetatable is not Lua's getmetatable. It has been overwritten by a function that returns nil for at least some values. Trivial function getmetatable() end