我用的linux版本是乌班图14.04,用到的lua版本是lua5.1
在ubuntu下lua的安装包,binary和dev是分开装的
sudo apt-get install lua5.1
sudo apt-get install liblua5.1-dev
add.lua
function add(a, b)
return a + b;
end
C代码
add.cp
#include <stdio.h>
#include <string.h>
#include <lua5.1/lua.h>
#include <lua5.1/lualib.h>
#include <lua5.1/lauxlib.h>
/* The lua interpreter */
lua_State *L;
int luaadd(int x, int y)
{
int sum;
/* the function name */
lua_getglobal(L, "add");
/* the first argument */
lua_pushnumber(L, x);
/* the second argument */
lua_pushnumber(L, y);
/* call the function with 2 arguments, return 1 result. */
lua_call(L, 2, 1);
/* get the result */
sum = (int)lua_tonumber(L, -1);
/* cleanup the return */
lua_pop(L, 1);
return sum;
}
int main (int argc, char **argv)
{
int sum;
/* initialize lua */
L = lua_open();
/* load lua base libraries */
luaL_openlibs(L);
/* load the script */
luaL_dofile(L, "add.lua");
/* call the add function */
sum = luaadd(10, 15);
/* print the result */
printf("The sum is %d \n", sum);
/* cleanup lua */
lua_close(L);
return 0;
} /* -----End of main()----- */
编译运行add.c时需要需要连接lua5.1的库
-l参数就是用来指定程序要链接的库,-l参数紧接着就是库名
在ubuntu下lua的安装包,binary和dev是分开装的
sudo apt-get install lua5.1
sudo apt-get install liblua5.1-dev
add.lua
function add(a, b)
return a + b;
end
C代码
add.cp
#include <stdio.h>
#include <string.h>
#include <lua5.1/lua.h>
#include <lua5.1/lualib.h>
#include <lua5.1/lauxlib.h>
/* The lua interpreter */
lua_State *L;
int luaadd(int x, int y)
{
int sum;
/* the function name */
lua_getglobal(L, "add");
/* the first argument */
lua_pushnumber(L, x);
/* the second argument */
lua_pushnumber(L, y);
/* call the function with 2 arguments, return 1 result. */
lua_call(L, 2, 1);
/* get the result */
sum = (int)lua_tonumber(L, -1);
/* cleanup the return */
lua_pop(L, 1);
return sum;
}
int main (int argc, char **argv)
{
int sum;
/* initialize lua */
L = lua_open();
/* load lua base libraries */
luaL_openlibs(L);
/* load the script */
luaL_dofile(L, "add.lua");
/* call the add function */
sum = luaadd(10, 15);
/* print the result */
printf("The sum is %d \n", sum);
/* cleanup lua */
lua_close(L);
return 0;
} /* -----End of main()----- */
编译运行add.c时需要需要连接lua5.1的库
-l参数就是用来指定程序要链接的库,-l参数紧接着就是库名
gcc add.c -I /usr/include/lua5.1 -llua5.1