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

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

如下面的Hello代码:

环境:Ubuntu + lua5.1

--HelloLua.lua
--Author : Wing
function 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库
	//TODO
	Hello(L);
	//end
	lua_close(L); 
	printf("end\n");
	return 0; 
}

编译和运行:

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值