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,
); /* get argument */
lua_pushnumber(L, sin(d));
/* push result */
return
;
/* number of results */
}
int main()
{
float pi =
3.1415926;
float pidiv6 = pi /
;
float pidiv4 = pi /
;
float rt =
;
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());
;
}
lua_getglobal(L,
"lsin");
lua_pushnumber(L, pidiv4);
if ( !lua_pcall(L,
, , ) ) {
rt = lua_tonumber(L, -);
}
else {
printf());
;
}
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);
, , )
) {
rt = lua_tonumber(L, -);
} else {
printf());
;
}