C语言调用Lua脚本

来源:互联网 发布:java 入门 编辑:程序博客网 时间:2024/05/17 23:26

最近由于公司技术需要,开始研究lua,刚开始看文档知道lua是一个脚本,用于拓展的,今天就研究了一下在c语言中的调用。

我是看到了一个文档,然后照着做的:

http://www.cnblogs.com/pied/archive/2012/10/26/2741601.html

不过这个文档可能是时间久了,有的地方不是那么顺利,下面是我的每一步的操作。

 

 

首先介绍一下我的环境,我是在centos7上运行的,最开始是通过yuminstall lua安装的,但是这个liblua这个文件不知道安装到哪里去了,出现了一些问题

这个问题按照文档的说法,先updatedb,然后locatelua.h,就是搜索不到,出现下面的页面:

并不是像作者说的那样有一个lua.h这个结果,后面各种尝试,还是不行,然后我就删除掉yum安装的yum rermove lua,然后rm –rf /usr/bin/lua。

我发现是我的环境的问题,我就在lua 的官网http://www.lua.org/,去下载了一个源码包,不过这个版本是5.3的

①wget http://www.lua.org/ftp/lua-5.3.3.tar.gz

②tar zxf lua-5.3.3.tar.gz

③cd lua-5.3.3

④make linux test

好了,安装好了之后,输入lua 是没有效果的,我做了一个链接,进入到src中之后输入:ln lua /usr/bin/lua。

接着编译文件gcc –o testtest.c

但是还是报错,错误信息是这样的:

就遇到了和作者一样的第二个问题,先updatedb一下,然后locateliblua

然后在后面添加-llua就可以编译通过了,然后./test跑出来,由于我改了lua代码,所以结果会不一样:

 

好了,现在在c中调用lua成功了

 

附:

C语言代码:

//add.c

 

#include        <stdio.h>

#include        "lua.h"

#include        "lualib.h"

#include        "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;

}

 

 

Lua代码:

function add(x,y)

      return x + y * 100

end

 

 

 

by:ChamPly 

2016年7月2日

0 0