从C查询Lua用户数据类型 [英] Query Lua userdata type from C

查看:53
本文介绍了从C查询Lua用户数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有某种元表类型的Lua用户数据对象(例如"stackoverflow.test").从C代码开始,我希望能够准确地检查它是哪种类型,并根据结果进行不同的处理.是否有一个方便的函数(就像luaL_checkudata一样,但是如果答案不是您想要的,也不会出错),让我查询userdata的元表类型名称?如果不是,我想我需要使用lua_getmetatable,但是我有点不清楚如何确定刚刚添加到堆栈中的元表的名称.

I have a Lua userdata object with a certain metatable type (e.g. "stackoverflow.test"). From C code, I want to be able to check exactly which type it is, and behave differently depending on the results. Is there a nice handy function (rather like luaL_checkudata, but without erroring if the answer isn't what you want) that let's me query the metatable type name of the userdata? If not, I guess I need to use lua_getmetatable, but then I'm a bit unclear how I determine the name of the metatable that's just been added to the stack.

仅需澄清一下:我使用的是Lua 5.1,其中luaL_checkudata的行为已更改.我知道在5.0中它不会出错.

Just to clarify: I'm using Lua 5.1, where the behaviour of luaL_checkudata was changed. I understand that in 5.0 it didn't used to error.

推荐答案

您将使用lua_getmetatablelua_equal来测试表是否相同.

You'll use lua_getmetatable and lua_equal for testing that the tables are the same.

在我看来,Lua应该为这种类型扩展的东西提供更多的支持.到目前为止,确实要由Lua/C(++)包装系统负责.

In my opinion, Lua should give more support to this kind of type-extending things. As of now, it's really on the responsibility of the Lua/C(++) wrapper system to do that.

在包装器中,我最近做过(作为商业项目的一部分),我做了class::instance(L,index)以获取特定类型的userdata指针.换句话说,该方法检查它是用户数据,并且该元表也正确.如果不是,则返回NULL.

In a wrapper I've done recently (as part of a commercial project) I do class::instance(L,index) to get userdata pointers of a particular type. In other words, that method checks that it's userdata and that the metatable is also right. If not, it returns NULL.

Lua可以帮助所有这一切的方法是,如果该元表具有用于扩展类型信息的标准字段(例如__type).可以这样使用,以便type()本身将返回"userdata","xxx"(两个值,当前仅返回一个值).这将与大多数当前代码保持兼容.但这只是假设(除非您执行自定义type()并自行实现).

The way Lua could help all this is if the metatable had a standard field for extended type information (s.a. __type). This could be used so that type() itself would return "userdata", "xxx" (two values, currently returning only one). This would remain compatible with most of current code. But this is just hypothetical (unless you do a custom type() and implement this on your own).

这篇关于从C查询Lua用户数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆