luabindでコルーチン

nil
記事: 428
登録日時: 13年前

luabindでコルーチン

投稿記事 by nil » 11年前

水没したパソコンはモニターも含め完全復活しました。
モニターは中に染みていた水が全部乾燥したようで元通りです。ヨカッタ...

luabindでコルーチンを使ってみます。
以下テストコードです。

CODE:

#include 
#include 
#include 

#pragma comment(lib, "lua5.1.lib")
#ifdef _DEBUG
#	pragma comment(lib, "luabind_mtd.lib")
#else
#	pragma comment(lib, "luabind_mt.lib")
#endif

int main() {
	lua_State* luaState = lua_open();
	luaL_openlibs(luaState);
	luabind::open(luaState);

	if(luaL_dofile(luaState, "test.lua")) {
        printf("%s\n", lua_tostring(luaState, lua_gettop(luaState)));
        lua_close(luaState);
        return -1;
	}

	luabind::object step = luabind::globals(luaState)["step"];

	try {
		while(1) {
			int res = luabind::resume_function(step);
			printf("%d\n", res);
		}
	}
	catch(...) {
		puts("end");
	}

	lua_close(luaState);

	return 0;
}

CODE:

--test.lua
function step()
  print("first");
  coroutine.yield(1);
  print("second");
  coroutine.yield(2);
  print("last");
  return 3;
end
GRAMさんのドキュメント和訳で特に困ること無く書けました。多謝。

コルーチンを使う時と使わない時の違いは関数の呼び出し程度。
call_functionをresume_functionに変えるだけです(?)。
Lua単体だとこう簡単には行きませんね。

但し、コルーチンが終了したかの判定方法がいまいちわからず、
終了後呼び出しの例外捕捉を使って無理やり終了させています。
(ドキュメントの"スレッド"周りを見ても何も書いていない……)

当面は返り値で終了したかどうかを捕捉ことになりそうです……。

ではでは(´・ω・)ノシ

コメントはまだありません。