Saturday, June 5, 2010

Luabind converter for QString

Luabind is a very convenient tool for binding C++ code to Lua. If you want to use Lua inside your Qt project then support for QString type is a must. By adding a little C++ template you can teach Luabind how to convert between QString and Lua string types. Just copy and paste the following code.
namespace luabind
{
    template <>
    struct default_converter
      : native_converter_base
    {
        static int compute_score(lua_State* L, int index)
        {
            return lua_type(L, index) == LUA_TSTRING ? 0 : -1;
        }

        QString from(lua_State* L, int index)
        {
            return QString(lua_tostring(L, index));
        }

        void to(lua_State* L, QString const& x)
        {
            lua_pushstring(L, x.toAscii());
        }
    };

    template <>
    struct default_converter
      : default_converter
    {};
}