您的位置:首页 > 编程语言 > Lua

关于lua中文教程上C API第一个lua与c交互示例程序编译 整理

2013-06-24 20:44 666 查看
示例代码如下,在ubuntu下如何编译通过
#include  <stdio.h>
#include  <lua.h>
#include  <lauxlib.h>
#include  <lualib.h>

int  main (void)
{
char buff[256];
int  error;
lua_State *L = lua_open();  /* opens Lua */
luaopen_base(L);   /* opens the basic library */
luaopen_table(L);    /* opens the table library */
luaopen_io(L);   /* opens the I/O library */
luaopen_string(L);  /* opens the string lib. */
luaopen_math(L);   /* opens the math lib. */

while  (fgets(buff, sizeof(buff), stdin) != NULL) {
error = luaL_loadbuffer(L, buff, strlen(buff),
"line") || lua_pcall(L, 0, 0, 0);
if (error) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);/* pop error message from the stack */
}
}

lua_close(L);
return 0;
}


1.安装readline和ncurses,这是为安装lua做准备

http://www.sfr-fresh.com/unix/misc/readline-6.1.tar.gz,下载readline, 然后解压tar -zxvf readline-6.1.tar.gz

进入解压目录cd readline-6.1

执行命令 ./configure && make && make install (可能会没有权限,sudo su切换到root下执行) 和 sudo ldconfig

http://ftp.gnu.org/pub/gnu/ncurses/ncurses-5.7.tar.gz,下载ncurses, 然后解压 tar -xvf ncurses-5.7.tar.gz

然后cd ncurses-5.7

执命令./configure && make && make install (和上面一样,没有权限则到root下)和sudo ldconfig

2.下载安装lua 去这下载http://www.lua.org/ftp/lua-5.1.4.tar.gz,解压,进入目录,输入出命令make linux

然后sudo make install OK了,环境搭好了。

3.编译上面的示例代码,代码文件为。test.c吧

进入test.c所在目录,输入 cc -o test test.c -llua -lm -ldl进行编译。会发现有错误。

原因是少了一个strlen的头文件,#include <string.h>和示例中代码是lua5.0环境的。

可做如下修改

#include  <stdio.h>
#include  <string.h>
#include  <lua.h>
#include  <lauxlib.h>
#include  <lualib.h>
#include  <string.h>

int  main (void)
{
char buff[256];
int  error;
printf("begin\n");
lua_State *L = lua_open();  /* opens Lua */
luaL_openlibs(L);////这里
while  (fgets(buff, sizeof(buff), stdin) != NULL) {
error = luaL_loadbuffer(L, buff, strlen(buff),
"line") || lua_pcall(L, 0, 0, 0);
if (error) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);/* pop error message from the stack */
}
}

lua_close(L);

printf("end\n");
return 0;
}

再次编译可以成功了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: