微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Lua入门

   最近两天没啥事,在研究一个开源游戏,发现其中用了Lua脚本语言,这个东西从来没接触过,所以在网上找了些个入门的小例子学习,但是过程中出现了许多的错误

首先在网上读了一篇入门教程,有个例子可是却编译不过。

开发环境:OS:CentOS5.3 32位

          Lua 5.2

代码如下:

文件 e12.lua

 
 
  1. -- add two numbers 
  2. function add ( x, y ) 
  3.   return x + y 
  4. end 

 

文件 e13.cpp

 
 
  1. #include <stdio.h> 
  2. extern "C" 
  3.     #include "lua.h"    
  4.     #include "lualib.h"    
  5.     #include "lauxlib.h"    
  6. }    
  7.  
  8. lua_State* L;    
  9. int luaadd ( int x, int y )    
  10. {    
  11.     int sum;    
  12.     lua_getglobal(L, "add");    
  13.     lua_pushnumber(L, x);    
  14.     lua_pushnumber(L, y);    
  15.     lua_call(L, 2, 1);    
  16.     sum = (int)lua_tonumber(L, -1);    
  17.     lua_pop(L, 1);    
  18.     
  19.     return sum;    
  20. }    
  21. int main ( int argc, char *argv[] )    
  22. {    
  23.     int sum;    
  24.     L = lua_open();    
  25.     lua_baselibopen(L);    
  26.     lua_dofile(L, "e12.lua");    
  27.     sum = luaadd( 10, 15 );    
  28.     printf( "The sum is %d\n", sum );    
  29.  
  30.     lua_close(L);    
  31.     
  32.     return 0;    

编译方法

g++ e13.cpp -llua -llualib -o e13

然后发现出现错误

e13.cpp: In function ‘int main(int,char**)’:
e13.cpp:31: error: ‘lua_open’ was not declared in this scope
e13.cpp:34: error: ‘lua_baselibopen’ was not declared in this scope
e13.cpp:38: error: ‘lua_dofile’ was not declared in this scope

在参看了网上其他的例子以后将调用函数修改为:

 
 
  1. L = lua_open()// luaL_newstate();  
  2. lua_baselibopen(L); //  luaL_openlibs(L);  
  3. lua_dofile(L, "e12.lua");// luaL_dofile(L, "e12.lua"); 

然后编译出现以下错误

/usr/bin/ld: cannot find -llualib
collect2: ld returned 1 exit status

搜索了一些文档将编译方法修改为:

 g++ e13.cpp -o e13 -I/usr/local/include /usr/local/lib/liblua.a -llua -ldl

编译通过,执行:

./e13

The sum is 25

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐