编写一个简单的C++供Lua调用的计时器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了编写一个简单的C++供Lua调用的计时器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2359字,纯文字阅读大概需要4分钟。
内容图文
// -----------------------------------------Timer------------------------------------ #include "stdafx.h" #include "windows.h" #include <iostream> #include <fstream> #include <string> usingnamespace 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 ) { return0; } times =1; } LUALIB_API int settimer(lua_State *L) //启动Timer;{ if ( L == nullptr ) { return0; } times = luaL_checkint(L,-1); //获取参数;constchar *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)) { constchar* error = lua_tostring(L,-1); cout<<string(error)<<endl; } if(lua_pcall(L,0,0,0)) { constchar* error = lua_tostring(L,-1); return0; } } } 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)) { constchar* error = lua_tostring(L,-1); cout<<string(error)<<endl; } if(lua_pcall(L,0,0,0)) { constchar* 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)) { constchar* error = lua_tostring(L,-1); cout<< string(error)<<endl; return0; } text(); lua_close(L); //系统命令,暂停; system("pause"); return0; }
以上是C++部分的代码 ,实际上只是一个简单的计时器,实际生产中并没有什么用途 , 因为不可能只用一个计时器,所以要通过面向对象的思想将其封装,用实例化ID来控制开启和关闭多个计时器;
以下是LUA测试代码和执行结果
i=0--计数变量,用于停止timerfunction prints() --timer循环体print("this is a timer") i=i+1if i == 10then stoptimers() endendfunction a() --开始Timerprint("this is a timer") settimer(0.1,"prints",0) endfunction main() --入口print("hello word") a() print("hello word") end
从以上测试代码中我们可以看出 我们settimer设置的参数是 0.1 funame 0
就是说每隔0.1s无限调用funame函数
而funame函数中则设置了循环10次后就执行停止timer的操作
所以循环只执行了10次即结束
原文:http://www.cnblogs.com/Black-Crow/p/5151491.html
内容总结
以上是互联网集市为您收集整理的编写一个简单的C++供Lua调用的计时器全部内容,希望文章能够帮你解决编写一个简单的C++供Lua调用的计时器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。