1

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?

Zsolt DOKA
  • 13
  • 2

1 Answers1

2

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
Piglet
  • 27,501
  • 3
  • 20
  • 43
  • Thanks for the elaborative answer! There was some confusion on my part as to how Lua handles structs that are usually objects in other business languages. C++ exported objects have the possibility to include their data in a metatable, which seemed exclusive; however the actual object representations can be of the type Lua table themselves, which I totally missed. – Zsolt DOKA Apr 21 '21 at 21:36