call lua function from c and called back to c

Just a simple example:


--The  c file:

#include <stdio.h>

#include "lua.h"

#include "luaconf.h"

#include "lualib.h"

#include "lauxlib.h"

#include "math.h"


static int l_sin (lua_State *L) {

double d = lua_tonumber(L, 1);  /* get argument */

   lua_pushnumber(L, sin(d));  /* push result */

    return 1 /* number of results */

}


int main()

{

float pi = 3.1415926;

float pidiv6 = pi / 6;

float pidiv4 = pi / 4;


float rt = 0;


lua_State *L = luaL_newstate();

luaL_openlibs(L);


lua_pushcfunction(L, l_sin); //Lua know the address of l_sin in c context

lua_setglobal(L, "mysin"); //map l_sin to mysin will be called in lua context


if ( !luaL_dofile(L, "./cal.lua") ) {

printf("load cal.lua successful\n");

} else {

printf("error load file: %s\n", lua_tostring(L, -1));

        return -1;

}


lua_getglobal(L, "lsin");

lua_pushnumber(L, pidiv4);

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

rt = lua_tonumber(L, -1);

} else {

printf("error : %s\n", lua_tostring(L, -1));

        return -1;

}


printf("rt = %f\n", rt);


return 0;

}


--cal.lua

print("start...")
function lsin ( angle )
return mysin(angle)
end
print("end...")


==output==

start...
end...
load cal.lua successful
rt = 0.707107


//Actually a more simpler way is to call mysin directly without cal.lua

lua_getglobal(L, "mysin");

lua_pushnumber(L, pidiv4);

if ( !lua_pcall(L, 110) ) {

rt = lua_tonumber(L, -1);

else {

printf("error : %s\n", lua_tostring(L, -1));

        return -1;

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值