lua_touserdata返回null

时间:2013-09-03 12:05:47

标签: objective-c lua 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);    

如果我错过了什么,请告诉我!

我的LuaCode代码段:

local library = require('plugin.user')

local userInfo = library.newUserInfo()
print(userInfo.getUserName())

更新 在使用lua_upvalueindex(1)之后,我摆脱了null这将引用回到用户信息实例。

UserInfo **userInfo = (UserInfo**)lua_touserdata(L,lua_upvalueindex( 1 ));

希望它也有助于其他人!

2 个答案:

答案 0 :(得分:2)

我认为这可能是你处理userdata的metatable的方式。具体来说,我认为你从createUserInfo()返回的是一个表而不是用户数据。我建议你创建一次metatable,例如在luaopen中,然后在新的userdata上设置它。像这样......

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");
    ...

答案 1 :(得分:0)

lua_upvalueindex(1)修复了nil错误。

UserInfo **userInfo = (UserInfo**)lua_touserdata(L,lua_upvalueindex( 1 ));

我想简要解释实际发生的事情。 C中的函数将获得传递给方法的一堆参数。 Lua在线文档有一个Array示例,其中所有方法都采用数组实例的第一个参数。所以,lua_touserdata(L,1)工作正常,因为第一个参数是数组实例。

来自lua.org的示例显示

a = array.new(10) --size 10
array.insert(a, 1, 1) --array.insert(instance, index, value). 

lua_touserdata(L,1)作为第一个参数是数组实例。

在我的情况下,我在没有任何参数的情况下调用实例方法。所以,lua堆栈在我的C函数中是空的,而lua_touserdata(L,1)抛出了null。

示例:

a = array.new(10)
a.showValues()  --the method is not over array. it is called on instance.

因此,为了访问showValues中的实例,我需要调用lua_touserdata(L,lua_upvalueindex(1))。这将给出数组实例对象。