lua-users home
lua-l archive

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


It was thus said that the Great Ranier Vilela once stated:
> Em sex., 26 de fev. de 2021 às 22:25, Sean Conner <sean@conman.org>
> escreveu:
> 
> >         * You cleanup the stack, thus removing the stack entry with the
> >           userdata.
> >
> In your opinion, this code is correct?
> 
> if (lua_getmetatable(L, 2)) {
>     lua_getfield(L, -1, "namefield");
>     if (lua_isuserdata(L, -1)) {
>          MyCtype func = (MyCtype) lua_touserdata(L, -1);
>           int n = 1;
> 
>           if (func != NULL) {
>               void * child = lua_touserdata(L, 2);
> 
>               control = (*func)(child);
>               ++n; /* pop child */
>           }
>           lua_pop(L, n); /* pop child and MyCType */
>      }
> }

  I would write this as:

	int mylua_func(lua_State *L)
	{
	  MyCtype func = luaL_checkudata(L,2,"MyCtype");
	  
	  /*-------------------------------------------------------------
	  ; func will NOT be null, if the stack item isn't a userdata or
	  ; have the proper metatable, luaL_checkudata() will throw an
	  ; error.  You also do NOT need the casts if you writing in C.  If
	  ; this is C++, then yes, you will need the cast.
	  ;--------------------------------------------------------------*/
	  
	  if (luaL_getmetafield(L,2,"namefield"))
	  {
	    /*-----------------------------------------------------------
	    ; luaL_getmetafield() will return 1 if there is a field of the
	    ; given name in the metatable, and push the item on the stack. 
	    ; It will return 0 and NOT push any data if the field doesn't
	    ; exist.
	    ;-------------------------------------------------------------*/
	    
	    (*func)(luaL_checkudata(L,-1,"myothertype"));
	    lua_pop(L,1);
	  }
	}

  The auxilary library has a lot of convenience functions.
  
  -spc