lua-users home
lua-l archive

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


On Mon, Sep 19, 2005 at 10:11:50AM +1000, Shaun wrote:

> Just wondering if there is any collected wisdom about the fastest/nicest 
> way of determining the type of userdata passed into a C function (from 
> LUA).
> 
> For example, assuming I have a function that can accept three different 
> types of userdata (which are actually C++ objects), how do you generally 
> go about determining which of the three types it is efficiently?

There are many "standard" ways to do this, but they all involve maps
from the userdata metatable to something on the C/C++ side.  Here's one
approach that maps userdata metatables to C++ RTTI information:

  // 
  // WARNING: code is untested and my C++ is a bit rusty, but this
  // should be close to what you want...
  // 

  void get_cpp_table(lua_State*L)
  {
    // pointer to use as table index, should be unique to this process
    static const volatile int marker = 0;

    lua_pushlightuserdata(L,static_cast<const void*>(&marker));
    lua_rawget(L,LUA_REGISTRYINDEX);

    // if it doesn't exist, create it...
    if (lua_isnil(L,-1)) {
      lua_pop(L,1);
      lua_newtable(L);
      lua_pushlightuserdata(L,static_cast<const void*>(&marker));
      lua_pushvalue(L,-2);
      lua_rawset(L, LUA_REGISTRYINDEX);
    }
  }

  std::type_info const* get_type_info(lua_State* L,int index)
  {
    if (!lua_getmetatable(L,index)) return NULL;
    get_cpp_table(L);
    lua_insert(L,-2);
    lua_rawget(L,-2);
    
  }

  int add_type_info( lua_State* L, int mt, std::type_info const& info )
  {
    if (!lua_istable(L,mt)) return 0;

    get_cpp_table(L);
    lua_pushvalue(L,mt);
    lua_pushlightuserdata(L, static_cast<const void*>(&info));
    lua_rawset(L,-3);
    lua_pop(L,1);

    return 1;
  }

[...]

>    luaL_getmetatable(L, "Class");
> 
>    int ok = lua_rawequal(L, -1, -2);

I've found that lookup tables are faster for this kind of switch-like
behavior.  This is true for most Lua objects, including strings if
they've already been interned.

Best,

-- 
Shannon Stewman         | Let us walk through the waning night,
Caught in a whirlpool,  | As dawn-rays tickle our toes, the dew soothes
A quartering act:       | Our blistered soles, and damp bones stir
Solitude or society?    | As crimson cracks under the blue-grey sky.