新建func1.lua文件,文件内容:
func1 = function ( a,b ) return a+b end同目录新建test.c文件
#include <stdio.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" lua_State *L = NULL; // 内部调用lua函数 double func1(double x, double y){ double z; lua_getglobal(L, "func1"); // 获取lua全局函数func1() lua_pushnumber(L, x); // 压入参数x和y lua_pushnumber(L, y); //参数数量,结果数量,错误处理函数索引 if(lua_pcall(L, 2, 1, 0) != 0) error(L, "error running function 'func1': %s", lua_tostring(L, -1)); //如果lua函数返回多个结果,第一个结果先入栈 //如函数返回3个结果,第一个结果索引为-3 if(!lua_isnumber(L, -1)) error(L, "function 'func1' must return a number"); z = lua_tonumber(L, -1); lua_pop(L, 1); return z; } int main(void){ L = luaL_newstate(); //打开Lua,创建一个新环境(新的Lua状态) luaL_openlibs(L); //打开标准库, 如: print, pcall //加载func1.lua文件 if (luaL_loadfile(L,"func1.lua")|| lua_pcall(L, 0, 0, 0) ){ error(L,"can not run config file: %s",lua_tostring(L,-1)); } printf("%f\n", func1(1.0, 2.0)); lua_close(L);//关闭lua状态 return 0; }编译代码:
gcc -lm -g -o test test.c /usr/local/lib/liblua.a -ldl