Skip to content

Commit

Permalink
check error of calling member function by wrong syntax: obj.func()
Browse files Browse the repository at this point in the history
  • Loading branch information
peacalm committed Aug 26, 2024
1 parent 518afbf commit 5a6d5dd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
6 changes: 5 additions & 1 deletion include/peacalm/luaw.h
Original file line number Diff line number Diff line change
Expand Up @@ -4336,7 +4336,11 @@ struct luaw::registrar<Return (Class::*)(Args...)> {
static void register_member_function(luaw& l,
const char* fname,
MemberFunction&& mf) {
auto f = [=](ObjectType o, Args... args) -> Return {
auto f = [mf, &l](ObjectType o, Args... args) -> Return {
if (!o) {
luaL_error(l.L(), "Calling member function by null pointer of object");
return Return();
}
PEACALM_LUAW_ASSERT(o);
return mf(*o, std::move(args)...);
};
Expand Down
46 changes: 46 additions & 0 deletions test/unit_test/register_member.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ struct Obj {
int cv_geti() const volatile { return i; }

int plus() { return ++i; }
int plusby(int d) {
i += d;
return i;
}

void reset() { i = 0; }

int overloaded_f() { return i + 1000; }
int overloaded_f() const { return i + 2000; }
Expand Down Expand Up @@ -346,6 +352,46 @@ TEST(register_member, member_functions) {
EXPECT_EQ(l.gettop(), 0);
}

TEST(register_member, member_functions_by_wrong_syntax_call) {
luaw l;

l.register_member("i", &Obj::i);
l.register_member("plus", &Obj::plus);
l.register_member("plusby", &Obj::plusby);
l.register_member("reset", &Obj::reset);

Obj o;
l.set("o", &o);

int ret_code = l.dostring("o.plus()");
EXPECT_NE(ret_code, LUA_OK);
l.log_error_out();
EXPECT_EQ(o.i, 1);

bool failed;
int reti = l.eval_int("return o.plus()", -1, false, &failed);
EXPECT_EQ(reti, -1);
EXPECT_TRUE(failed);

ret_code = l.dostring("o:plus()");
EXPECT_EQ(ret_code, LUA_OK);
EXPECT_EQ(o.i, 2);

ret_code = l.dostring("o:reset()");
EXPECT_EQ(ret_code, LUA_OK);
EXPECT_EQ(o.i, 0);

ret_code = l.dostring("o.plusby(3)");
EXPECT_NE(ret_code, LUA_OK);
l.log_error_out();
EXPECT_EQ(o.i, 0);

EXPECT_EQ(l.eval_int("return o.plusby(o, 5)"), 5);
EXPECT_EQ(l.eval_int("return o:plusby(5)"), 10);

EXPECT_EQ(l.gettop(), 0);
}

TEST(register_member, result_status_of_get) {
luaw l;
l.set("o", Obj{});
Expand Down

0 comments on commit 5a6d5dd

Please sign in to comment.