如何在用户数据中存储值类型?

How to store a value type in a userdata?

This SO article is the same thing, 但答案没有帮助,因为答案在 Lua 中,而问题是关于 C-API。所以我再问一次。希望其他人将从这个问题中受益。

我实际上有 2 个问题(我无法让 y 和 z 工作,我也无法让 helloworld() 工作)

我正在努力做到这一点:

local x = MyCBoundLib.GetSomething()
print(x.y)
print(x.z)

其中 x 是用户数据。我不断收到 attempt to index a userdata value

我知道“userdata isn't indexable without a metatable because it's C/C++ data

在我的 C 代码中,我做了类似的事情来尝试包装对象。

int push_Something(lua_State *L, void *object)
{
    struct SomethingWrapper *w = (struct SomethingWrapper *)lua_newuserdata(L, sizeof(struct SomethingWrapper));
    w->object = object;

    luaL_setmetatable(L, "Something");
    return 1;
}

早些时候,我尝试注册一个名为 Something 的元表,如下所示:

luaL_newmetatable(L, "Something");
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, some_funcs, 0);
lua_pop(L, 1);

其中 some_funcs 有:

static luaL_Reg const some_funcs [] =
{
    { "helloworld",     l_helloworld },
    { NULL, NULL }
};

如果我尝试 print(x.helloworld()),我会得到同样的错误:attempt to index a userdata value

在我的代码的 none 中,我知道如何正确附加值类型 yz.

首先,helloworld 您的代码有效:

/* file: hw.c
 * on Debian/Ubuntu compile with:
 *  `gcc -I/usr/include/lua5.2 -fpic -shared -o hw.so hw.c`
 */
#include <lua.h>
#include <lauxlib.h>

struct SomethingWrapper {
  void *object;
};

static int l_helloworld(lua_State *L) {
  lua_pushliteral(L, "Hello World!");
  return 1;
}

static luaL_Reg const some_funcs[] = {
  { "helloworld", l_helloworld },
  { NULL, NULL }
};

int push_Something(lua_State *L, void *object) {
  struct SomethingWrapper *w = lua_newuserdata(L, sizeof(*w));
  w->object = object;
  luaL_setmetatable(L, "Something");
  return 1;
}

int luaopen_hw(lua_State *L) {
  luaL_newmetatable(L, "Something");
  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");
  luaL_setfuncs(L, some_funcs, 0);
  lua_pop(L, 1);

  push_Something(L, NULL);
  return 1;
}

和测试脚本:

-- file: hwtest.lua
local x = require( "hw" )
print( x.helloworld() )

输出为:

Hello World!

要访问用户数据的属性,您需要将 __index 设置为函数而不是 table。每当您尝试访问用户数据上的字段时,都会使用两个参数(用户数据和密钥)调用该函数,您可以查询 C object 并推送所需的结果。

如果您打算同时支持方法和属性,它会变得有点复杂,但基本方法如下:您使用一个函数作为 __index 元方法。此函数可以访问 table 方法(例如通过上值或注册表等)并尝试在 table 中查找给定的键。如果你成功了,你 return 那个值。如果您一无所获,则将给定的密钥与 C object 的有效 属性 名称进行比较,如果匹配,则将 return 各自的值进行比较。 (如果你没有得到匹配,你可以 return nil 或提出错误 - 这取决于你。)

这是该方法的可重用实现(摘自 moon toolkit):

static int moon_dispatch( lua_State* L ) {
  lua_CFunction pindex;
  /* try method table first */
  lua_pushvalue( L, 2 ); /* duplicate key */
  lua_rawget( L, lua_upvalueindex( 1 ) );
  if( !lua_isnil( L, -1 ) )
    return 1;
  lua_pop( L, 1 );
  pindex = lua_tocfunction( L, lua_upvalueindex( 2 ) );
  return pindex( L );
}

MOON_API void moon_propindex( lua_State* L, luaL_Reg const methods[],
                              lua_CFunction pindex, int nups ) {
  if( methods != NULL ) {
    luaL_checkstack( L, nups+2, "not enough stack space available" );
    lua_newtable( L );
    for( ; methods->func; ++methods ) {
      int i = 0;
      for( i = 0; i < nups; ++i )
        lua_pushvalue( L, -nups-1 );
      lua_pushcclosure( L, methods->func, nups );
      lua_setfield( L, -2, methods->name );
    }
    if( pindex ) {
      lua_pushcfunction( L, pindex );
      if( nups > 0 ) {
        lua_insert( L, -nups-2 );
        lua_insert( L, -nups-2 );
      }
      lua_pushcclosure( L, moon_dispatch, 2+nups );
    } else if( nups > 0 ) {
      lua_replace( L, -nups-1 );
      lua_pop( L, nups-1 );
    }
  } else if( pindex ) {
    lua_pushcclosure( L, pindex, nups );
  } else {
    lua_pop( L, nups );
    lua_pushnil( L );
  }
}

用法:

/*  [ -nup, +1, e ]  */
void moon_propindex( lua_State* L,
                     luaL_Reg const* methods,
                     lua_CFunction index,
                     int nup );

This function is used for creating an __index metafield. If index is NULL but methods is not, a table containing all the functions in methods is created and pushed to the top of the stack. If index is not NULL, but methods is, the index function pointer is simply pushed to the top of the stack. In case both are non NULL, a new C closure is created and pushed to the stack, which first tries to lookup a key in the methods table, and if unsuccessful then calls the original index function. If both are NULL, nil is pushed to the stack. If nup is non-zero, the given number of upvalues is popped from the top of the stack and made available to all registered functions. (In case index and methods are not NULL, the index function receives two additional upvalues at indices 1 and 2.) This function is used in the implementation of moon_defobject, but maybe it is useful to you independently.

如果您尝试在用户数据中存储任意 Lua 值(如标题所示)——您不能。但是您可以将额外的 table(称为 "uservalue")与每个用户数据相关联,并在其中存储任意值。该方法类似于上面的方法,但不是与预定义的 属性 名称匹配并直接访问 C object,而是首先推送用户值 table(使用 lua_getuservalue)和然后在那里查找您的领域。