反反复复学lua N多次了,这次终于在C中调用lua成功了!一大进步啊!
记录下过程:
1、找到代码如下:
//add.c
#include <stdio.h>#include "lua.h"#include "lualib.h"#include "lauxlib.h"/*the lua interpreter*/lua_State* L;intluaadd(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;}intmain(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.add的代码如下
--add two numbersfunction add(x,y)
return x + yend然后,尝试编译:gcc -o add add.c
提示: fatal error: lua.h: No such file or directory
然后,locate lua.h,无果。。。
原来在ubuntu下lua的安装包,binary和dev是分开装的,找了一下,需要安装另外一个包liblua5.1-dev
唔,装好了还是需要用-I指定,所以先找下lua.h被放哪里的。
sudo updatedb
locate lua.h
显示的结果:
/home/zxluo/Documents/backup/Work/luascript/AndroLua/jni/lua/lua.h
/usr/include/lua5.1/lua.h
/usr/include/lua5.1/lua.hpp
/usr/src/linux-headers-3.2.0-23-generic/include/config/scsi/dh/alua.h
/usr/src/linux-headers-3.2.0-24-generic/include/config/scsi/dh/alua.h
所以,添加文件再次编译:gcc -o add add.c -I /usr/include/lua5.1/
出现提示:
/tmp/ccPtEQyI.o: In function `luaadd':
main.c:(.text+0x23): undefined reference to `lua_getfield'
main.c:(.text+0x37): undefined reference to `lua_pushnumber'
main.c:(.text+0x4b): undefined reference to `lua_pushnumber'
main.c:(.text+0x64): undefined reference to `lua_call'
main.c:(.text+0x78): undefined reference to `lua_tonumber'
main.c:(.text+0x93): undefined reference to `lua_settop'
/tmp/ccPtEQyI.o: In function `main':
main.c:(.text+0xac): undefined reference to `luaL_newstate'
main.c:(.text+0xc2): undefined reference to `luaL_openlibs'
main.c:(.text+0xd6): undefined reference to `luaL_loadfile'
main.c:(.text+0xf8): undefined reference to `lua_pcall'
main.c:(.text+0x133): undefined reference to `lua_close'
collect2: ld returned 1 exit status
那个啥,是没有把库link过来,gcc不知道要把这些函数ld到哪里去,继续找liblua:
locate liblua
打印结果:
/usr/lib/x86_64-linux-gnu/liblua5.1-c++.a
/usr/lib/x86_64-linux-gnu/liblua5.1-c++.so
/usr/lib/x86_64-linux-gnu/liblua5.1-c++.so.0
/usr/lib/x86_64-linux-gnu/liblua5.1-c++.so.0.0.0
/usr/lib/x86_64-linux-gnu/liblua5.1.a
/usr/lib/x86_64-linux-gnu/liblua5.1.so
/usr/lib/x86_64-linux-gnu/liblua5.1.so.0
/usr/lib/x86_64-linux-gnu/liblua5.1.so.0.0.0
所以添加编译选项:gcc -o add main.c -I /usr/include/lua5.1 -llua5.1
哦也~这下没有错误了
你可以改动add.lua试试,比如在x+y后面再+10! 啊哈, what happened?
amazing script!
——————
无论在哪里做什么,只要坚持服务、创新、创造价值,其他的东西自然都会来的。