lua 和c++

1、压栈函数

test.lua代码

function lua_call_back_func(arg1, arg2)
    print(arg1 + arg2)
    return arg1 + arg2
end

local table_week = {osmUploadDll.getLoadData(lua_call_back_func)}
print(table_week)

c++代码

static int getLoadDataFunc(lua_State *L)
{

    luaL_checktype(L, 1, LUA_TFUNCTION);    
    int aa = 11, bb = 33;
    lua_pushnumber(L, aa);
    lua_pushnumber(L, bb);
    //lua_call(L, 2, 0);
    int ret1 = lua_pcall(L, 2, 1,0);
    printf("sum1:%d + %d = %ld\n", aa, bb, lua_tointeger(L, -1));

    return 1;

}

static const struct luaL_Reg myLib[] =
{
    {"getLoadData",getLoadDataFunc},
    {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
};

int luaopen_UploadDll(lua_State *L)
{
    lua_newtable(L);
    luaL_setfuncs(L, myLib, 0);
    return 1; // 把myLib表压入了栈中,所以就需要返回1 
}

 

2、c++直接调用lua函数

lua文件sample_2.lua

print("lua script addfun.lua have been load ")
function lua_func(arg1, arg2)
    return arg1 + arg2
end

c++文件

static int getLoadDataFunc(lua_State *L)
{    

    //对Lua Code 函数进行调用
    int a = 11;
    int b = 12;
    lua_getglobal(L1, "lua_func");               //调用lua中的函数sum
    lua_pushinteger(L1, a);
    lua_pushinteger(L1, b);
    int ret = lua_pcall(L1, 2, 1, 0);
    printf("sum:%d + %d = %ld\n", a, b, lua_tointeger(L1, -1));

    lua_pop(L1, 1);
    lua_close(L1);

    return 1;

}

static const struct luaL_Reg myLib[] =
{
    {"getLoadData",getLoadDataFunc},
    {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
};

int luaopen_UploadDll(lua_State *L)
{
    lua_newtable(L);
    luaL_setfuncs(L, myLib, 0);
    return 1; // 把myLib表压入了栈中,所以就需要返回1 
}

3、c++调用lua文件

test.lua文件

oUploadDll = require 'oUploadDll';

local openstate = oUploadDll.openDB("","","","","123")
print(openstate)
local isopen = oUploadDll.isDBOpen()
print(isopen)
local openstate1 = oUploadDll.closeDB()
print(openstate1)
local isopen1 = ooploadDll.isDBOpen()
print(isopen1)

c++文件

static const struct luaL_Reg myLib[] =
{

{"openDB",openDBFunc},
    {"isDBOpen",isDBOpenFunc},
    {"closeDB",closeDBFunc},
    {"getLoadData",getLoadDataFunc},
    {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
};

int luaopen_UploadDll(lua_State *L)
{
    lua_newtable(L);
    luaL_setfuncs(L, myLib, 0);
    return 1; // 把myLib表压入了栈中,所以就需要返回1 
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值