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
    {};
}

3 comments:

  1. This is wonderful! But I think the first template should read:

    struct default_converter
    : native_converter_base

    and the second:

    struct default_converter
    : default_converter

    ReplyDelete
  2. ...ugh. I mean, of course:

    struct default_converter<QString>
    : native_converter_base<QString>

    and

    struct default_converter<QString const&>
    : default_converter<QString>

    So it was probably the html filter in the first place.

    ReplyDelete
  3. Thanks hakeliha. Do you do any interesting stuff with lua? If so then drop me an email.

    ReplyDelete