Add ObjectRef:is_valid method

This commit is contained in:
Lars Mueller 2024-06-21 18:42:55 +02:00
parent 0ad415c18d
commit 0810275640
4 changed files with 18 additions and 2 deletions

@ -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.

@ -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})

@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "lua_api/l_object.h"
#include <cmath>
#include <lua.h>
#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<ObjectRef>(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),

@ -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);