PS:参考自《lua游戏开发指南》
事件驱动的程序可以增强系统的可扩展性——lua游戏开发指南原话
书中的事件驱动程序主要分为几个重要的部分,是lua与c/++的双向交互。
1、提供一个luaGlue函数在lua中注册事件处理函数。
2、c/c++代码获取事件处理函数名称,在c/c++中调用lua编写的事件处理函数。
3、必须保证lua与c/c++中事件id的一致。
lua代码:
EVENT_SAMPLE = 1000
RegisterEvent("EventHandler")
function EventHandler( id, ...)
myFile = io.open( "io.lua", "w" )
myFile:write("ddddd")
if id == EVENT_SAMPLE then
myFile:write( "sample event!!! ")
end
io.close(myFile)
end
//基于事件消息驱动的lua-c/c++交互模型
/*--
----lua利用luaGlue函数注册事件
----c/c++调用lua函数执行事件
--*/
#include <iostream>
#include <string>
extern "C"
{
#include <lua\lua.h>
#include <lua\lualib.h>
#include <lua\lauxlib.h>
}
//定义时间id,注意与lua一致
#define EVENT_SAMPLE 1000
std::string g_strEventHandler = "";
extern "C"
{
//lua事件处理函数注册的luaGlue函数
int _RegisterEvent( lua_State* L )
{
g_strEventHandler = luaL_optstring( L, 1, "" ); //取得第一个参数。
return 0;
}
}
//c++发出调用
void FireEvent( lua_State*L, int id )
{
if( g_strEventHandler != "" )
{
char buf[254];
sprintf( buf, "%s(%d)", g_strEventHandler.c_str(), id );
int err = luaL_dostring( L, buf ); //调用lua程序块
//std::string errStr = lua_tostring( L, -1 );
}
}
int main()
{
lua_State* L = lua_open();
luaL_openlibs( L );
//lua_register( L, "RegisterEvent", _RegisterEvent);
lua_pushcfunction( L, _RegisterEvent );
lua_setglobal( L, "RegisterEvent" );
luaL_dofile( L,"eventDriven.lua" );
FireEvent( L, 1000 );
return 0;
}
后记:唉,好忧伤,效率好低,各种各样的事情总是让你无法静下心来,也有自己意志不够强的原因,晚上总是很想睡觉。。囧,剩下的时间估计也不多了,至少得吧把lua和opengl给过一遍。还有操作系统,c++,windows网络编程模型的什么的....还有毕设开题,也得赶快有个说法....唉~,~好忧伤
The end~~~~~~~~
原文:http://blog.csdn.net/coderling/article/details/18820959