是否可以从C中调用Lua脚本中的一个特定函数?目前,我有一个调用C函数的Lua脚本。现在,我需要这个C函数来调用上述脚本中的一个Lua函数。
编辑:C函数如下所示:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static double E1(double x) {
double xint = x;
double z;
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, "luascript.lua");
lua_pcall(L, 0, 0, 0);
lua_getglobal(L, "func");
lua_pushnumber(L, x);
lua_pcall(L, 1, 1, 0);
z = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_close(L);
return z;
}
static int Ret(lua_State *L){
double y = lua_tonumber(L, -1);
lua_pushnumber(L, E1(y));
return 1;
}
int luaopen_func2lua(lua_State *L){
lua_register(
L,
"Ret",
Ret
);
return 0;
}Lua脚本如下所示:
require "func2lua"
function func (x)
-- some mathematical stuff
return value
end
x = 23.1
print(Ret(x)) -- Ret is the C function from the top c-file发布于 2016-05-13 13:06:13
是的你可以。C函数将需要一种获得该函数的方法。根据您的需求,您可以将该Lua函数作为参数之一传递给C函数,也可以将该Lua函数存储在C可以到达的地方--无论是在全局环境中(然后C将lua_getglobal()该函数)还是在属于该脚本的某个预定义表中。
https://stackoverflow.com/questions/37210362
复制相似问题