学习小记--用C语言调用lua代码的Hello程序

来源:互联网 发布:python灰帽子下载 编辑:程序博客网 时间:2024/06/16 21:02

使用API 调用函数的方法实现c调lua函数:首先,将被调用的函数入栈;第二,依次将所有参数入栈;第三,使用lua_pcall 调用函数;最后,从栈中获取函数执行返回的结果。

如下面的Hello代码:

环境:Ubuntu + lua5.1

--HelloLua.lua--Author : Wingfunction Hello(str)print(str)return "Self: Hello Wing!"end

 

//HelloC.c//Author : Wing#include  <unistd.h>#include  <stdio.h> #include  <string.h>#include  <lua.h> #include  <lauxlib.h> #include  <lualib.h>void Hello(lua_State *L) { if(luaL_loadfile(L,"./HelloLua.lua")){//加载lua程序error(L,"loadfile failed");}/*这里加这句,是因为loadfile仅仅视编译lua文件,并不执行这个文件,也就是说只是在栈上形成一个匿名函数,只有执行这个函数一次才会使得Hello可以通过getGlobal获取,否则全局变量为空*/lua_pcall(L, 0, 0, 0);lua_getglobal(L, "Hello" );//获取lua代码中的Hello函数 lua_pushstring(L, "Wing: Hello Self!");//传入参数/* 执行函数 (1 参数, 1 返回结果) */ /*第三个参数是errfunc, If errfunc is 0, then the error message returned on the stack is exactly the original error message. Otherwise, errfunc is the stack index of an error handler function.*/  if (lua_pcall(L, 1, 1, 0) != 0) {  error(L, "error running function `Hello': %s", lua_tostring(L, -1));}/* 接收返回值 */   if (!lua_isstring(L, -1)) {  error(L, "function `Hello' must return a string" );}  const char* rt = lua_tostring(L, -1);//取出返回值printf("%s\n", rt);//打印 lua_pop(L, 1); /*把栈中返回值pop出来*/}int  main (void){printf("begin\n");lua_State *L = lua_open();  luaL_openlibs(L);//加载lua库//TODOHello(L);//endlua_close(L); printf("end\n");return 0; }

编译和运行:

cyd@ubuntu:~/Desktop/lua$ cc  -o Hello HelloC.c -llua -lm -ldl cyd@ubuntu:~/Desktop/lua$ ./HellobeginWing: Hello Self!Self: Hello Wing!endcyd@ubuntu:~/Desktop/lua$ 

 

原创粉丝点击