lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello Lua,

  lua can only push lightuserdata into the stack, but sometimes we
  need push a full userdata.

  When I wrote a gui system in lua, the widget in C get the message
  from os first, and then I need convert the widget to the lua object
  for dispatching the message. In fact , my widget have a pointer
  return by lua_newuserdata , but there is no api to convert back this
  pointer to a lua object.

  Now, I create a weak table in registry. Then use luaL_ref to get a
  reference of the object, and save the reference number in my widget.
  When I need convert the pointer back to the lua object, I can use
  the reference number to lookup that weak table .

  But I think it's a expensive way, Adding a new api lua_pushuserdata
  to convert the pointer back will much cheaper.

  --------------
LUA_API void lua_pushuserdata (lua_State *L, void *p) {
  Udata *u;
  lua_lock(L);
  u = cast(Udata *,p) - 1;
  setuvalue(L, L->top, u);
  api_incr_top(L);
  lua_unlock(L);
}
  --------------

  This api would be unsafe, because the pointer p may be not a
  userdata alloc by lua , or the userdata has already been collected.
  But we can use it on our own risk. If someone use it in a wrong way,
  it's not lua's fault.

-- 
Best regards,
 Cloud                          mailto:cloudwu@163.com
            http://blog.codingnow.com

[吾生也有涯, 而知也无涯]