</pre><pre name="code" class="cpp">
对c/c++ 与lua的交互调用函数做一个小总结
#include <iostream>
extern "C" {
#include "lua.h"
#include <lauxlib.h>
#include <lualib.h>
}
/*
-- lua 文件内的内容
a = 10
function show(param)
return a + param
end
*/
int main()
{
// 建立一个state 区域
lua_State* L = luaL_newstate();
// opens the basic library 这些是在引入一些库
luaL_openlibs(L);
// 读取lua文件 读取成功返回0, 失败返回非零整数
if(luaL_dofile(L,"lua_prac.lua") != 0)
{
printf("文件lua_prac.lua读取失败");
return 0;
}
// 将lua中的函数名压入栈中
lua_getglobal(L,"show");
// 将参数传入函数show中
lua_pushnumber(L,3);
// 调用函数
lua_pcall(L,1,1,0);
// 将函数的返回结果取出来 即nResult
int nResult = lua_tointeger(L,-1);
printf("%d",nResult);
getchar();
return 0;
}
以上例子能正常运行的条件是有lua-5.1.5中的lua.h文件 和lua51.lib文件找得到, 一般都是加一下附加目录