linux c运行lua函数,Lua入门之四:Lua调用C/C++库(函数压栈方式)

前面讲过Lua载入dll的方式去调用函数库,下面介绍的是函数压栈的方式调用函数库,通过lua_register把函数注册到lua的栈中,lua_register的定义如下,

#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))

看了定义就知道,其实就是函数压栈,然后设置为全局变量,这样lua就可以调用它了。

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

//

#include "stdafx.h"

#include

#include

#include

#include

#include

//lua头文件

#ifdef __cplusplus

extern "C" {

#include "lua.h"

#include

#include

}

#else

#include

#include

#include

#endif

#pragma comment(lib, "lua51.lib")

static int math_abs(lua_State *L)

{

//获取传入的参数

lua_pushnumber(L, abs((int)luaL_checknumber(L, 1)));

return 1;

}

static int math_cos(lua_State *L)

{

lua_pushnumber(L, cos((double)luaL_checknumber(L, 1)));

return 1;

}

static int math_sin(lua_State *L)

{

lua_pushnumber(L, sin((double)luaL_checknumber(L, 1)));

return 1;

}

static const luaL_reg mathlib[] = {

{ "abs", math_abs },

{ "cos", math_cos },

{ "sin", math_sin },

{ NULL, NULL }

};

static int ShowMessage(lua_State * L)

{

lua_pushnumber(L, 1000);

printf("show message and push 1000 \n");

return -1;

}

int main(int argc, char** argv)

{

lua_State* L = lua_open();

luaL_openlibs(L);

// lua_register(L, "cos", math_cos);

// lua_register(L, "sin", math_sin);

// lua_register(L, "abs", math_abs);

//#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))

luaL_register(L, "DY_MATH", mathlib);

char *luapath="./script/lua/lua.lua";

luaL_dofile(L, luapath);

double sinv = 30*3.1415926/180.0;

lua_getglobal(L, "SIN");

lua_pushnumber(L, sinv);

if (0 != lua_pcall(L, 1, 1, 0))

{

printf("cpp call lua function failed\n");

}

printf("sin(%f)=%f\n", sinv, lua_tonumber(L, -1));

lua_pop(L, 1);

lua_getglobal(L, "COS");

lua_pushnumber(L, 0.5);

if (0 != lua_pcall(L, 1, 1, 0))

{

printf("cpp call lua function failed\n");

}

printf("cos(0.5)=%f\n", lua_tonumber(L, -1));

lua_pop(L, 1);

//压栈后设置一个lua可调用的全局函数名

lua_pushcfunction(L, ShowMessage);

lua_setglobal(L, "showmessage");

//c调用lua

lua_getglobal(L, "SHOWMESSAGE");

lua_pcall(L, 0, 0, 0);

printf("get the showmessage pushed value %f \n", lua_tonumber(L, -1));

lua_close(L);

}

---------------------------------------------

--region lua.lua

--Date

--此文件由[BabeLua]插件自动生成

function COS(a)

print("called COS in lua script")

--lua调用c/c++

return DY_MATH.cos(a)

end

function SIN(a)

print("called SIN in lua script")

return DY_MATH.sin(a)

end

function SHOWMESSAGE()

showmessage()

end

--endregion

Lua 的详细介绍:请点这里

Lua 的下载地址:请点这里

0b1331709591d260c1c78e86d0c51c18.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值