lua 5.1不会为用户数据在C++中注册__tostring函数

我刚刚接触lua,试图掌握C API。发现我不能为我的用户数据注册__tostring函数,但如果我像__index那样通过设置字段来实现,它就开始工作了。我做错了什么?

#define GRID_META "denisbaic.gridmanager"

#define checkgrid(L) \
*static_cast<GridManager**>(luaL_checkudata(L,1,GRID_META))

if (luaL_newmetatable(L, GRID_META)) // grid_mt
{
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");

    luaL_Reg arraylib_m[] = {
        {
            "__gc", [](lua_State* L)
            {
                auto const grid_manager_ptr = checkgrid(L);
                delete grid_manager_ptr;
                luaL_error(L, "hello");
                return 0;
            }
        },

        {
            "__tostring ",[](lua_State* L) //it's doesnt work
            {
                luaL_error(L,"hello");//the author's way to find out that lua has entered a function
                auto const grid_manager_ptr = checkgrid(L);
                size_t const string_len = grid_manager_ptr->Size.x * grid_manager_ptr->Size.y;

                ostringstream oss("");
                for (int temp = 0; temp < string_len; temp++)
                    oss << grid_manager_ptr->GetMapPtr()[temp];

                lua_pushlstring(L, oss.str().c_str(), string_len);
                return 1;
            }
        },
    { nullptr, nullptr }
    };
luaL_register(L, nullptr, arraylib_m);//for metatable
}
点赞