1.lua函数如下:
--add.lua
function add(a,b)
return a+b
end
2.c调用lua的函数,代码如下:
#include <stdio.h>
#include "lua.h"
int main(int argc, char const *argv[])
{
/* code */
lua_State* L = luaL_newstate();
if((luaL_loadfile(L,"./add.lua")) || (lua_pcall(L,0,0,0)))
{
fprintf(stderr, "error:%s\n", lua_tostring(L,-1));
return;
}
lua_getglobal(L,"add"); //function to be called
lua_pushnumber(L,5); //1st args
lua_pushnumber(L,10); //2st args
/* do the call (2 arguments, 1 result) */
if (lua_pcall(L, 2, 1, 0) != 0)
error(L, "error running function `f': %s",lua_tostring(L, -1));
/* retrieve result */
if (!lua_isnumber(L, -1))
error(L, "function `add' must return a number");
double c = lua_tonumber(L, -1);
lua_pop(L, -1); /* pop returned value */
fprintf(stderr, "c = %g\n",c);
lua_close(L);
return 0;
}