【发布时间】:2016-05-13 12:41:57
【问题描述】:
是否可以只从 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
【问题讨论】:
-
你不能用C写这个lua函数吗?通常是 lua 调用 C 而不是其他方式
-
不幸的是,第三个程序依赖于 Lua。所以,对我来说,没有办法绕过它。
-
也许对 Lua 文件的一些解释会有所帮助。当您执行 Lua 文件时,它: 1) 加载并运行 func2lua.lua,将全局
func设置为函数值,将全局x设置为数字,调用全局Ret变量的值作为函数并将全局print变量的值作为函数调用。在设置func之前,它的值将是nil。目前还不清楚你想给谁打电话,什么时候打电话。您可能不想多次加载和执行文件。