call lua function from c and called back to c
Posted mfmdaoyou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
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, 1, 1, 0) ) {
rt = lua_tonumber(L, -1);
} else {
printf("error : %s\n", lua_tostring(L, -1));
return -1;
}
以上是关于call lua function from c and called back to c的主要内容,如果未能解决你的问题,请参考以下文章
[WASM] Call a JavaScript Function from WebAssembly
Calling Matlab function from python: “initializer must be a rectangular nested sequence”