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

4 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
  4. Casino 2021 - Mapyro
    Casino 영주 출장마사지 2021. Find your 청주 출장샵 ideal location in Greater Boston. Explore our 대구광역 출장안마 selection of slot 춘천 출장안마 machines, table games, blackjack, roulette 광주 출장마사지 and more.‎Borgata Hotel · ‎Atlantic City Casino & Spa

    ReplyDelete