U E D R S I H C RSS
ID
Password
Join
열정이 없는 인생은 자유가 없는 인생과도 같다. -- 앤터니 퀸

대상 C++ 클래스 내에 object 맴버변수를 가지고 있으면 됩니다. 이를 .property()를 사용하여 지정하면 매우 편리하게 간단한 콜백기능을 추가할 수 있습니다. (이 클래스로 생성된 루아 클래스 인스턴스는 각각의 인스턴스마다 서로 다른 콜백함수를 설정할 수 있고, 이를 C++상에서 호출할 수 있는 구조가 됩니다!) 이때, object를 C++ 함수의 매개변수로 사용할 때 nil값이 넘어갈 경우 형변환이 성공한다는 점과(결과값은 NULL이 됩니다), invalid한 object는 luabind::error 예외에 걸리지 않는다는 점을 조심해야합니다. 아래 예제는 test_class를 루아상에 구현하기 위한 대비용 Wrapper C++ 클래스와 이 클래스를 루아상에 생성하기위한 함수와 클래스 인스턴스내에서 onTest 콜백을 실행하기위한 C++ 함수에 대한 소스입니다.
struct test_class {
	luabind::object onTest_;
	void set_onTest(luabind::object f_) { onTest_ = f_; }
	luabind::object get_onTest() const { return onTest_; }
};

test_class* test_create() {
	test_class* new_test_obj_ = new test_class();
	return new_test_obj_;
}

void test_member(luabind::object o_) {
	test_class* tmpObj_ = NULL;
	try {
		tmpObj_ = luabind::object_cast<test_class*>(o_);
		if (!tmpObj_) {
			printf("nil을 매개변수로 쓰지 마십시요!\n"); 			return;
		}
	}
	catch(luabind::cast_failed &e) {
		printf("test_class 타입의 매개변수가 아닙니다.\n"); 		return;
	}
	try {
		if (tmpObj_->onTest_) 
			tmpObj_->onTest_(tmpObj_, “테스트문자열”);
		else 
			printf("onTest를 지정하지 않았습니다.\n");
	}
	catch(luabind::error &e) {
		printf("theTest가 함수가 아닙니다.\n");
	}
}

module(l)
[
	def("putline", &putline_),
	def("getline", &getline_, pure_out_value(_1)),
	class_<test_class>("test_class")
	   .property(	"onTest", 
		     	&test_class::get_onTest, 
			&test_class::set_onTest),
	def("test_create", &test_create, adopt(return_value)),
	def("test_member", &test_member)
]
아래는 이를 실행하기위한 루아 코드와 실행결과입니다.
a=test_create()
a.onTest = function(self, txt_) print(“a!!!”) end
b=test_create()
function b:onTest(txt_) print(“b!!!!”, txt_) end
c=test_create()
test_member(a)
test_member(b)
test_member(c)
test_member(1)
test_member(nil)
a!!!
b!!!!	 테스트문자열
onTest를 지정하지 않았습니다.
theTest가 함수가 아닙니다.
nil을 매개변수로 쓰지 마십시요!

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2010-10-28 12:42:52
Processing time 0.5148 sec