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

示例代码如下,在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; 
}

再次编译可以成功了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值