简体   繁体   English

Lua - C++ object 元表返回零

[英]Lua - C++ object metatable returns nil

I have just started delving into Lua, and I learnt that C++ object properties could be accessible through metatables.我刚刚开始研究 Lua,我了解到 C++ object 属性可以通过元表访问。

I am trying to access such an object's functions in a game's script: " GameLib ".我试图在游戏脚本中访问这样一个对象的功能:“ GameLib ”。 It is available in Lua as a global variable, but getmetatable() returns nil:它在 Lua 中作为全局变量可用,但getmetatable()返回 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?是否存在 C++ object 没有元表的情况? If so, is there another way to access its properties?如果是这样,还有其他方法可以访问其属性吗?

From the Lua 5.4 Reference Manual:来自 Lua 5.4 参考手册:

2.4 Metatables and Metamethods: 2.4 元表和元方法:

Every value in Lua can have a metatable. Lua 中的每个值都可以有一个元表。

By default, a value has no metatable , but the string library sets a metatable for the string type默认情况下,一个值没有 metatable ,但字符串库为字符串类型设置了一个 metatable

So there are cases where values, even userdata have no metatable.所以有些情况下,值,甚至用户数据都没有元表。 In fact that's default.事实上,这是默认的。

6.1 Basic Functions: getmetatable 6.1 基本函数:getmetatable

If object does not have a metatable, returns nil.如果 object 没有元表,则返回 nil。 Otherwise, if the object's metatable has a __metatable field, returns the associated value.否则,如果对象的元表具有 __metatable 字段,则返回关联的值。 Otherwise, returns the metatable of the given object.否则,返回给定 object 的元表。

So the that leaves us with two options why getmetatable(GameLib) returns nil :所以这给我们留下了两个选择,为什么getmetatable(GameLib)返回nil

  1. GameLib does not have a metatable GameLib没有元表
  2. getmetatable is not Lua's getmetatable . getmetatable不是 Lua 的getmetatable It has been overwritten by a function that returns nil for at least some values.它已被 function 覆盖,至少对某些值返回 nil。 Trivial function getmetatable() end琐碎function getmetatable() end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM