最近两天没啥事,在研究一个开源游戏,发现其中用了Lua脚本语言,这个东西从来没接触过,所以在网上找了些个入门的小例子学习,但是过程中出现了许多的错误。
首先在网上读了一篇入门教程,有个例子可是却编译不过。
开发环境:OS:CentOS5.3 32位
Lua 5.2
代码如下:
文件 e12.lua
- -- add two numbers
- function add ( x, y )
- return x + y
- end
文件 e13.cpp
- #include <stdio.h>
- extern "C"
- {
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- }
- lua_State* L;
- int luaadd ( int x, int y )
- {
- int sum;
- lua_getglobal(L, "add");
- lua_pushnumber(L, x);
- lua_pushnumber(L, y);
- lua_call(L, 2, 1);
- sum = (int)lua_tonumber(L, -1);
- lua_pop(L, 1);
- return sum;
- }
- int main ( int argc, char *argv[] )
- {
- int sum;
- L = lua_open();
- lua_baselibopen(L);
- lua_dofile(L, "e12.lua");
- sum = luaadd( 10, 15 );
- printf( "The sum is %d\n", sum );
- lua_close(L);
- 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
在参看了网上其他的例子以后将调用函数修改为:
- L = lua_open(); // luaL_newstate();
- lua_baselibopen(L); // luaL_openlibs(L);
- 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
转载于:https://blog.51cto.com/wenbo/766350