本人最近学了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