//-----------------------------------------Timer------------------------------------ #include "stdafx.h" #include "windows.h" #include <iostream> #include <fstream> #include <string> using namespace std; extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #pragma comment(lib,"lualib.lib") lua_State * L; int times =0; LUALIB_API int stoptimers(lua_State *L) //停止Timer { if ( L == nullptr ) { return 0; } times =1; } LUALIB_API int settimer(lua_State *L) //启动Timer; { if ( L == nullptr ) { return 0; } times = luaL_checkint(L,-1); //获取参数; const char *funame = luaL_checkstring(L,-2); float sec = luaL_checknumber(L,-3); int i = 0; while(times==0 || i<times) //执行函数循环体 三个参数依次是执行间隔,执行函数名,执行次数(若为0则无限循环执行) ; { Sleep(1000*sec); cout<<i<<endl; i++; cout<<"调取LUA中函数"<<endl; lua_getglobal(L,funame); if(!lua_isfunction(L,-1)) { const char* error = lua_tostring(L,-1); cout<<string(error)<<endl; } if(lua_pcall(L,0,0,0)) { const char* error = lua_tostring(L,-1); return 0; } } } void text() { cout<<"LUA调用C++函数"<<endl; //将LUA需要调用的C++函数注册到LUA lua_pushcfunction(L,settimer); lua_setglobal(L,"settimer"); lua_pushcfunction(L,stoptimers); lua_setglobal(L,"stoptimers"); cout<<"调取LUA中函数"<<endl;//LUA入口 lua_getglobal(L,"main"); if(!lua_isfunction(L,-1)) { const char* error = lua_tostring(L,-1); cout<<string(error)<<endl; } if(lua_pcall(L,0,0,0)) { const char* error = lua_tostring(L,-1); return; } } int main ( int argc, char *argv[] ) { L = luaL_newstate(); //加载lua标准库; luaL_openlibs(L); //加载脚本 ; char* str = "E:\\B.lua"; if (luaL_loadfile(L,str)||lua_pcall(L,0,0,0)) { const char* error = lua_tostring(L,-1); cout<< string(error)<<endl; return 0; } text(); lua_close(L); //系统命令,暂停; system("pause"); return 0; }
以上是C++部分的代码 ,实际上只是一个简单的计时器,实际生产中并没有什么用途 , 因为不可能只用一个计时器,所以要通过面向对象的思想将其封装,用实例化ID来控制开启和关闭多个计时器;
以下是LUA测试代码和执行结果
i=0 --计数变量,用于停止timer function prints() --timer循环体 print("this is a timer") i=i+1 if i == 10 then stoptimers() end end function a() --开始Timer print("this is a timer") settimer(0.1,"prints",0) end function main() --入口 print("hello word") a() print("hello word") end
从以上测试代码中我们可以看出 我们settimer设置的参数是 0.1 funame 0
就是说每隔0.1s无限调用funame函数
而funame函数中则设置了循环10次后就执行停止timer的操作
所以循环只执行了10次即结束