简体   繁体   English

Lua C ++用户数据

[英]Lua C++ userdata

I am trying to access the type of a userdata so that I can process it accordingly. 我正在尝试访问用户数据的类型,以便可以对其进行相应的处理。 Imagine I have a class named as Foo: 想象一下,我有一个名为Foo的类:

class Foo:public CObject
{
 public:
 Foo():CObject(){}
 int type() {return 1;}
}

class CObject
{
 public:
 virtual int type(void)=0;
}

The rationale is that every class extending the CObject has a type that must be made known by an integer number (later on an enum). 基本原理是,扩展CObject的每个类都必须具有一个必须由整数知道的类型(此后是枚举)。 The class Foo is bind to lua using luaWwrapper (// https://bitbucket.org/alexames/luawrapper/src/fd9c4fdbf4b25034e3b8475a2c8da66b7caab427?at=default ). 使用luaWwrapper(// https://bitbucket.org/alexames/luawrapper/src/fd9c4fdbf4b25034e3b8475a2c8da66b7caab427?at=default )将Foo类绑定到lua。

  Foo* Foo_new(lua_State* L)
  {
    Foo* f=new Foo();
    lua_newuserdata(L,sizeof(f));
    std::cout<<"f="<<f;
    return f;
  }

In Lua user calls this as: 在Lua中,用户将此称为:

f=Foo.new() 
print(f)

Now I have a C++ function, say print: 现在我有一个C ++函数,比如print:

int lua_print(lua_State* L)
{
   void *ud = luaL_checkudata(L, 1, "Foo"); //ud is not zero
    std::cout<<"ud="<<ud;
    CObject* obj=(CObject*)ud;  //Casting to CObject
   int objtype=obj->type();   //program CRASHES here

} }

I have seen that the program crashes cause the memory addresses of Foo and ud are not the same. 我已经看到程序崩溃导致Fooud的内存地址不同。 I assume ud refers to the memory of stack which contains the memory adress of Foo . 假设 ud是指包含Foo的内存地址的堆栈内存。 How can I access stack's memory address or the preferred memory address of Foo ? 如何访问堆栈的内存地址或Foo的首选内存地址?

You have to use placement new to initialize the object in the memory returned by lua_newuserdata . 您必须使用new放置来初始化lua_newuserdata返回的内存中的对象。

Something in the lines of 某些东西

void *ud = lua_newuserdata(L,sizeof(Foo));
new (ud) Foo();

Foo_new should just return the pointer to the object. Foo_new应该只返回指向对象的指针。

In other words, your Foo_new would look like this: 换句话说,您的Foo_new如下所示:

Foo* Foo_new(lua_State* L)
{
  return new Foo();
}

However, if you have no special initialization you need to do, you don't even need to write this function. 但是,如果您不需要进行特殊的初始化,则甚至不需要编写此函数。 This function is supplied for you by magical templates if you don't write one yourself. 如果您自己不写,那么神奇的模板将为您提供此功能。

When you want to get your Foo object from the Lua state, you do this: 当您想从Lua状态获取Foo对象时,请执行以下操作:

int lua_print(lua_State* L)
{
   Foo *ud = luaW_to<Foo>(L, 1); //ud is not zero
   std::cout<<"ud="<<ud;
   CObject* obj=(CObject*)ud;
   int objtype=obj->type();
}

If CObject is registered with LuaWrapper too, you don't even need to do the manual cast. 如果CObject也已在LuaWrapper中注册,则您甚至不需要手动进行转换。 You can just do luaW_to<CObject>(L, 1); 您可以只执行luaW_to<CObject>(L, 1);

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

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