Skip to content

Commit

Permalink
Fix raise error when trying to instantiate abstract classes from Lua
Browse files Browse the repository at this point in the history
  • Loading branch information
gilzoide committed Nov 4, 2023
1 parent 35d5f2e commit 3ec7684
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
20 changes: 14 additions & 6 deletions src/utils/Class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,21 @@ sol::optional<int64_t> Class::get_constant(const StringName& name) const {
}
}

Variant Class::construct(const sol::variadic_args& args) const {
GDExtensionObjectPtr obj_ptr = godot::internal::gdextension_interface_classdb_construct_object(class_name._native_ptr());
Object *obj = godot::internal::get_object_instance_binding(obj_ptr);
if (obj->has_method("_init")) {
obj->callv("_init", to_array(args));
Variant Class::construct(sol::this_state state, const sol::variadic_args& args) const {
auto class_db = ClassDBSingleton::get_singleton();
if (!class_db->can_instantiate(class_name)) {
luaL_error(
state,
"Class '%s' or its base class cannot be instantiated",
String(class_name).ascii().get_data()
);
}
return obj;

Variant new_obj = class_db->instantiate(class_name);
if (new_obj.has_method("_init")) {
variant_call_string_name(state, new_obj, "_init", args);
}
return new_obj;
}

bool Class::operator==(const Class& other) const {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/Class.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class Class {
const StringName& get_name() const;
sol::optional<int64_t> get_constant(const StringName& name) const;

Variant construct(const sol::variadic_args& args) const;
Variant construct(sol::this_state state, const sol::variadic_args& args) const;

bool operator==(const Class& other) const;

Expand Down
2 changes: 2 additions & 0 deletions test/lua_tests/class_construct.lua
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
local obj = assert(RefCounted:new(), "Constructing class failed")

assert(not pcall(function() return LuaObject:new() end), "Instantiating abstract class should raise an error")

0 comments on commit 3ec7684

Please sign in to comment.