lua与c互调--lua调用c

lua代码:

test.lua

width=1
height=2
function sum(a,b)
	return a+b
end

function mystrcat(a,b)
	return a..b
end

function mysum(a,b)
	return csum(a,b)
end


c代码:

// test2_1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>


extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};


#pragma comment(lib, "lua5.1.lib")




int csum(lua_State *l)
{
	int a=lua_tointeger(l,1);
	int b=lua_tointeger(l,2);
	lua_pushinteger(l,a+b);
	return 1;
}


int _tmain(int argc, _TCHAR* argv[])
{

	lua_State * l = luaL_newstate() ;        //创建lua运行环境
	if ( l == NULL ) return 0;
	int ret = 0 ;
	ret = luaL_loadfile(l,"test.lua") ;      //加载lua脚本文件
	if ( ret != 0 ) return 0;
	ret = lua_pcall(l,0,0,0) ;
	if ( ret != 0 )  return 0;
	lua_getglobal(l,"width");              //获取lua中定义的变量
	lua_getglobal(l,"height");
	printf("height:%ld width:%ld\n",lua_tointeger(l,-1),lua_tointeger(l,-2)) ;
	lua_pop(l,1) ;                        //恢复lua的栈
	int a = 11 ;
	int b = 12 ;
	lua_getglobal(l,"sum");               //调用lua中的函数sum
	lua_pushinteger(l,a) ;
	lua_pushinteger(l,b) ;
	ret = lua_pcall(l,2,1,0) ;//两个参数,一个返回值
	if ( ret != 0 )  return 0;
	printf("sum:%d + %d = %ld\n",a,b,lua_tointeger(l,-1)) ;
	lua_pop(l,1) ;  //恢复lua的栈
	const char str1[] = "hello" ;
	const char str2[] = "world" ;
	lua_getglobal(l,"mystrcat");          //调用lua中的函数mystrcat
	lua_pushstring(l,str1) ;
	lua_pushstring(l,str2) ;
	ret = lua_pcall(l,2,1,0) ;//两个参数,一个返回值
	if ( ret != 0 )  return 0;
	printf("mystrcat:%s%s = %s\n",str1,str2,lua_tostring(l,-1)) ;
	lua_pop(l,1) ;  //恢复lua的栈
	lua_pushcfunction(l,csum) ;         //注册在lua中使用的c函数
	lua_setglobal(l,"csum") ;           //绑定到lua中的名字csum
	lua_getglobal(l,"mysum");           //调用lua中的mysum函数,该函数调用本程序中定义的csum函数实现加法
	lua_pushinteger(l,a) ;
	lua_pushinteger(l,b) ;
	ret = lua_pcall(l,2,1,0) ;
	if ( ret != 0 )  return 0;
	printf("mysum:%d + %d = %ld\n",a,b,lua_tointeger(l,-1)) ;
	lua_pop(l,1) ;
	lua_close(l) ;                     //释放lua运行环境

	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值