WINDOW环境下,VS与Lua脚本的关联

最近被领导安排任务研究Lua在嵌入式二次开发中的应用,然而好像用不了。

不过毕竟下了些功夫研究了一番,所以打算将学到的东西分享一下,希望能有所帮助。


本文讲的主要是如何将使用Lua扩展自己所写的C语言:


所用软件: VS2010     LuaForWindows_v5.1.4-46


语言挺无力的,就直接拿代码讲解吧。具体函数的用法,可以在Programming in Lua这本书里找到,在第四章,理解也要自己看书。


在VS中编写如下代码:

//MOTOR_Control
//include的头文件,在Lua5.1的安装目录下可以找到
#include        <stdio.h>
#include        "lua.h"
#include        "lualib.h"
#include        "lauxlib.h"

/*the lua interpreter*/
lua_State* L;
//这里定义的是需要Lua脚本配置的最大速度,最大温度;以及主程序中反馈的电机速度与反馈温度。
int max_speed;
int max_temp;
int fdb_motor_speed = 950;
int fdb_temp = 70;
int alarm = 0;

int main()
{
/*initialize Lua*/
        L = lua_open();
/*load Lua base libraries*/
        luaL_openlibs(L);
/*load the script*/这个语句是将C程序和对应的Lua程序关联起来,需要注意的是,这里的路径需要用\\分割开来
        luaL_dofile(L, "F:\\Test_LUA\\c_test\\lua\\con_motor.lua");
/*读取用户配置文件Lua中的全局变量,并保存在C中的全局变量中*/
        lua_getglobal(L,"MAXVEL");
	lua_getglobal(L,"MAXTEM");
	max_speed = (int)lua_tonumber(L,-2);
	max_temp = (int)lua_tonumber(L,-1);
/*print the result to show whether we succeed*/
        printf("Max Velocity is %d\n",max_speed);
	printf("Max Temperature is %d\n",max_temp);
/*remove number from L, 清空栈*/
	lua_pop(L,2);

/*调用lua中用户自定义的公式,push function and arguments*/
	lua_getglobal(L,"userfuc1");
	lua_pushnumber(L,fdb_motor_speed);
	lua_pushnumber(L,fdb_temp);
/*计算结果并检验*/
	if(lua_pcall(L,2,1,0)!=0)
		printf("error");
	alarm = lua_tonumber(L,-1);
	lua_pop(L,1);

	printf("Alarm is %d\n",alarm);
        lua_close(L);
/*因为VS运行一下就会关闭,所以加一个getchar()来看结果*/
	getchar();
        return 0;
}

Lua文件的代码:

--configuration file for program

--Max velocity
MAXVEL = 1200
--Max temperature
MAXTEM = 70

--USER Function one to control alarm
--two inputs you can use
function userfuc1(fdbspeed,temp)
	local alarm = 0;
	if fdbspeed > 900 then
		alarm = 1
	end
	return alarm
end

代码简单的介绍:

VS中的C程序中,我没有进行任何的函数配置,变量赋值。(反馈速度和反馈温度假设是从传感器返回的值)

之后将C与Lua关联。

将Lua中配置的最大速度,最大温度赋给C中的全局变量

并且调用Lua中的函数,实现自定义功能函数:当反馈速度大于900时,报警,alarm = 1


VS运行结果:最大速度1200,最大温度70,由于反馈速度950>900,alarm报警

第一次写博客...图片没弄上来,手打一下显示结果:

 

Max Velocity is 1200
Max Temperature is 70
alarm is 1
   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值