diff --git a/sol/function_types_usertype.hpp b/sol/function_types_usertype.hpp index cfc08ca6..ccf884d2 100644 --- a/sol/function_types_usertype.hpp +++ b/sol/function_types_usertype.hpp @@ -165,6 +165,22 @@ struct usertype_indexing_function : base_function { return prelude(L); } }; + +struct fail_on_error : base_function { + int prelude(lua_State* L) { + const char* accessor = stack::get(L, 1 - lua_gettop(L)); + return luaL_error(L, "sol: attempt to index nil value \"%s\" on userdata (bad (mispelled?) key name or does not exist)", accessor); + } + + virtual int operator()(lua_State* L) override { + return prelude(L); + } +}; + +inline fail_on_error& failure_on_error() { + static fail_on_error f; + return f; +} } // function_detail } // sol diff --git a/sol/usertype.hpp b/sol/usertype.hpp index f3c08896..ebeb3b81 100644 --- a/sol/usertype.hpp +++ b/sol/usertype.hpp @@ -435,11 +435,17 @@ private: void build_function_tables() { int variableend = 0; if (!indexwrapper.empty()) { + if (indexfunc == nullptr) { + indexfunc = &function_detail::failure_on_error(); + } functions.push_back(std::make_unique("__index", indexfunc, std::move(indexwrapper))); metafunctiontable.push_back({ "__index", function_detail::usertype_call }); ++variableend; } if (!newindexwrapper.empty()) { + if (newindexfunc == nullptr) { + newindexfunc = &function_detail::failure_on_error(); + } functions.push_back(std::make_unique("__newindex", newindexfunc, std::move(newindexwrapper))); metafunctiontable.push_back({ "__newindex", indexwrapper.empty() ? function_detail::usertype_call : function_detail::usertype_call }); ++variableend;