Skip to content

Commit

Permalink
Passing classes by ref to function is broken #4
Browse files Browse the repository at this point in the history
  • Loading branch information
satoren committed Jan 25, 2016
1 parent 87d776a commit 4c19986
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
45 changes: 45 additions & 0 deletions include/kaguya/type.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,51 @@ namespace kaguya
template<typename T> struct lua_type_traits<T
, typename traits::enable_if<traits::is_const_reference<T>::value>::type> :lua_type_traits<typename traits::remove_const_reference<T>::type > {};



template<typename REF> struct lua_type_traits < REF
, typename traits::enable_if<traits::is_lvalue_reference<REF>::value && !traits::is_const<typename traits::remove_reference<REF>::type>::value>::type >
{
typedef void Registerable;

typedef REF get_type;
typedef REF push_type;
typedef typename traits::remove_reference<REF>::type T;

static bool strictCheckType(lua_State* l, int index)
{
return object_wrapper(l, index, metatableName<T>()) != 0;
}
static bool checkType(lua_State* l, int index)
{
return object_wrapper(l, index, metatableName<T>()) != 0;
}
static get_type get(lua_State* l, int index)
{
T* pointer = get_pointer(l, index, types::typetag<T>());
if (!pointer)
{
throw LuaTypeMismatch("type mismatch!!");
}
return *pointer;
}
static int push(lua_State* l, push_type v)
{
if (!available_metatable<T>(l))
{
lua_pushlightuserdata(l, const_cast<typename traits::remove_const<T>::type*>(&v));
}
else
{
typedef ObjectPointerWrapper<T> wrapper_type;
void *storage = lua_newuserdata(l, sizeof(wrapper_type));
new(storage) wrapper_type(&v);
class_userdata::setmetatable<T>(l);
}
return 1;
}
};

template<typename PTR> struct lua_type_traits < PTR
, typename traits::enable_if<traits::is_pointer<typename traits::remove_const_reference<PTR>::type>::value && !traits::is_function<typename traits::remove_pointer<PTR>::type>::value>::type >
{
Expand Down
19 changes: 19 additions & 0 deletions test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,24 @@ namespace t_03_function

}

void reffun(Foo& ref)
{
ref.setBar("BarBar");
}
void arg_class_ref(kaguya::State& state)
{
state["Foo"].setClass(kaguya::ClassMetatable<Foo>()
.addMember("setBar", &Foo::setBar)
);

Foo foo;
state["reffun"] = kaguya::function(reffun);

state["reffun"](kaguya::standard::ref(foo));
TEST_CHECK(foo.bar == "BarBar");
}


#if KAGUYA_USE_CPP11
void lambdafun(kaguya::State& state)
{
Expand Down Expand Up @@ -1379,6 +1397,7 @@ int main()
ADD_TEST(t_03_function::vector_and_map_to_table_mapping);
ADD_TEST(t_03_function::coroutine);
ADD_TEST(t_03_function::zero_to_nullpointer);
ADD_TEST(t_03_function::arg_class_ref);
#if KAGUYA_USE_CPP11
ADD_TEST(t_03_function::lambdafun);
#endif
Expand Down

0 comments on commit 4c19986

Please sign in to comment.