lua_touserdata返回null

kap*_*ser 6 lua objective-c luac

我很难尝试获取我的userInfo参考.我的一个方法是返回对象的实例.每次调用createUserInfo时,它都会将userInfoObject返回给lua.

但是,当我从Lua调用userInfo对象的方法时,我无法获取userInfo对象的引用(lua_touserdata(L,1))

static int getUserName (lua_State *L){
   UserInfo **userInfo = (UserInfo**)lua_touserdata(L,1);

   // The following is throwing null! Need help. 
   // Not able to access the userInfo object.
   NSLog(@"UserInfo Object: %@", *userInfo);       
}

static const luaL_reg userInstance_methods[] = {
  {"getUserName", getUserName},
  {NULL, NULL}
}

int createUserInfo(lua_State *L){

  UserInfo *userInfo = [[UserInfo alloc] init];
  UserInfoData **userInfoData = (UserInfoData **)lua_newuserdata(L, sizeof(userInfo*));
  *userInfoData = userInfo;

  luaL_openlib(L, "userInstance", userInstance_methods, 0);
  luaL_getmetatable(L, "userInfoMeta");
  lua_setmetatable(L, -2);

return 1;
}

// I have binded newUserInfo to the createUserInfo method.
// I have also created the metatable for this userInfo Object in the init method.
// luaL_newmetatable(L, "userInfoMeta");
// lua_pushstring(L, "__index");
// lua_pushvalue(L, -2);
// lua_settable(L, -3);
// luaL_register(L, NULL, userInstance_methods);    
Run Code Online (Sandbox Code Playgroud)

如果我遗漏了什么,请告诉我!

我的LuaCode片段:

local library = require('plugin.user')

local userInfo = library.newUserInfo()
print(userInfo.getUserName())
Run Code Online (Sandbox Code Playgroud)

更新 我在使用lua_upvalueindex(1)之后删除了null这将引用回到用户信息实例.

UserInfo **userInfo = (UserInfo**)lua_touserdata(L,lua_upvalueindex( 1 ));
Run Code Online (Sandbox Code Playgroud)

希望它也能帮助别人!

Ale*_*lex 2

我认为这可能是您处理用户数据元表的方式。具体来说,我认为您返回的createUserInfo()是表而不是用户数据。我建议您在 luaopen 中创建一次元表,然后将其设置在新的用户数据上。像这样的东西...

int createUserInfo(lua_State *L) {

  UserInfo *userInfo = [[UserInfo alloc] init];
  UserInfoData **userInfoData = (UserInfoData **)lua_newuserdata(L, sizeof(userInfo));
  *userInfoData = userInfo;

  luaL_getmetatable(L, "userInfoMeta");
  lua_setmetatable(L, -2);

  return 1;
}

LUALIB_API int luaopen_XXX(lua_State *L)
{
    luaL_newmetatable(L,"userInfoMeta");
    luaL_openlib(L, NULL, userInstance_methods, 0);
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");
    ...
Run Code Online (Sandbox Code Playgroud)