c/c++中调用lua

本人最近学了lua,做点记录。。

     要在c/c++中使用lua,当时首先是需要个lua的解析器啦。。。  从( http://www.lua.org/ ) 这个网站可以下到。本人是在这里下载的 lua5.3 的源码, 可以从 这个git库clone一份  本人的vs2013工程 ( https://git.oschina.net/liLinux/lua-5.3.git )。。已经做好了设置,可以生成lua编译器,解释器,以及静态库或者动态库都行。


   c中调用lua,很基础很简单。所以直接上代码

//callLua.lua  被c调用的lua中的内容

Width = 100;
Height = 100;

function f(x,y)
	return (x^2 * math.sin(y)) / (1 - x);
end

//.c文件

#include "stdafx.h"
#include <string.h>
#include <lua.hpp>
#include <stdlib.h>

#ifndef _DEBUG
#pragma comment(lib,"Static.lib")
#else
#pragma comment(lib,"Static_d.lib")
#endif // !_DEBUG

//===========
double f(double x, double y)
{
	double dReturn = 0.0;

	lua_State* L = luaL_newstate();
	luaopen_base(L);   // 加载Lua基本库
	luaL_openlibs(L);  // 加载Lua通用扩展库

//加载lua文件
	if (0 != luaL_loadfile(L, ".\\callLua.lua"))
		error(L, "load file failed: %s", lua_tostring(L, -1));
	if (0 != lua_pcall(L, 0, 0, 0))
		error(L, "cannot run configuration file: %s", lua_tostring(L, -1));

//获取lua中的全局变量
	lua_getglobal(L, "Width");
	if (!lua_isnumber(L, -1))
		error(L, "`Width' should be a number\n");
	printf("width: %lf, ", lua_tonumber(L, -1));
	lua_pop(L,1);

	lua_getglobal(L, "Height");
	if (!lua_isnumber(L,-1))
		error(L, "`Height' should be a number\n");
	printf("height %.lf\n", lua_tonumber(L, -1));
	lua_pop(L,1);

//调用lua中的函数
	/*push functions and arguments*/
	lua_getglobal(L, "f");  //函数要先入栈
	lua_pushnumber(L, x);   //参数正序入栈
	lua_pushnumber(L, y);

	/*do the call (2 arguments, 1 result*/
	if (0 != lua_pcall(L, 2, 1, 0))  //执行后会自动将函数和使用的参数弹出栈,并将返回值压入栈
		error(L, "Error runing function 'f':%s", lua_tostring(L, -1));

         /*retrieve result*/
	if (!lua_isnumber(L, -1))
		error(L, "functiogn 'f' must return a number");

	dReturn = lua_tonumber(L, -1);
	lua_pop(L, 1);

	lua_close(L);
	return dReturn;
}
void Test()
{
	printf("value: %lf\n", f(10, 12));
}

int _tmain(int argc, _TCHAR* argv[])
{
	Test();

	system("pause");
	return 0;
}


如何在lua脚本中调用c:可以查看本人的这篇Blog: http://blog.csdn.net/qq_30949367/article/details/51405331

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值