diff --git a/doc/lua_api.md b/doc/lua_api.md index b1412ca85..37dfb8004 100644 --- a/doc/lua_api.md +++ b/doc/lua_api.md @@ -7815,6 +7815,10 @@ child will follow movement and rotation of that bone. ### Methods +* `is_valid()`: returns whether the object is valid. + Objects may be invalidated either through explicit removal, + or implicitly between server steps by the engine. + **The below methods should only be called for valid objects.** * `get_pos()`: returns position as vector `{x=num, y=num, z=num}` * `set_pos(pos)`: * Sets the position of the object. diff --git a/games/devtest/mods/unittests/entity.lua b/games/devtest/mods/unittests/entity.lua index 6cc207234..71f8ec32a 100644 --- a/games/devtest/mods/unittests/entity.lua +++ b/games/devtest/mods/unittests/entity.lua @@ -71,13 +71,13 @@ local function test_entity_lifecycle(_, pos) -- with binary in staticdata local obj = core.add_entity(pos, "unittests:callbacks", "abc\000def") + assert(obj:is_valid()) check_log({"on_activate(7)"}) obj:set_hp(0) check_log({"on_death(nil)", "on_deactivate(true)"}) - -- objectref must be invalid now - assert(obj:get_velocity() == nil) + assert(not obj:is_valid()) end unittests.register("test_entity_lifecycle", test_entity_lifecycle, {map=true}) diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index bc5ddba5c..6baf146e5 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_object.h" #include +#include #include "lua_api/l_internal.h" #include "lua_api/l_inventory.h" #include "lua_api/l_item.h" @@ -106,6 +107,13 @@ int ObjectRef::l_remove(lua_State *L) return 0; } +// is_valid(self) +int ObjectRef::l_is_valid(lua_State *L) +{ + lua_pushboolean(L, getobject(checkObject(L, 1)) != nullptr); + return 1; +} + // get_pos(self) int ObjectRef::l_get_pos(lua_State *L) { @@ -2646,6 +2654,7 @@ const char ObjectRef::className[] = "ObjectRef"; luaL_Reg ObjectRef::methods[] = { // ServerActiveObject luamethod(ObjectRef, remove), + luamethod(ObjectRef, is_valid), luamethod_aliased(ObjectRef, get_pos, getpos), luamethod_aliased(ObjectRef, set_pos, setpos), luamethod(ObjectRef, add_pos), diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index 73264db10..3e6d01201 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -67,6 +67,9 @@ class ObjectRef : public ModApiBase { // remove(self) static int l_remove(lua_State *L); + // is_valid(self) + static int l_is_valid(lua_State *L); + // get_pos(self) static int l_get_pos(lua_State *L);