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 ");

} else {

printf("error load file: %s ", 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 ", lua_tostring(L, -1));

        return -1;

}


printf("rt = %f ", 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 ", lua_tostring(L, -1));

        return -1;

}



原文地址:https://www.cnblogs.com/mfmdaoyou/p/6800598.html