从 C 中调用 lua 脚本返回的函数
Call a function returned by a lua script from C
给定一个 lua 文件,例如
-- foo.lua
return function (i)
return i
end
如何使用 C API 加载此文件并调用返回的函数?
我只需要以 luaL_loadfile
/luaL_dostring
.
开头的函数调用
一个loaded块只是一个常规函数。从C加载模块可以这样想:
return (function() -- this is the chunk compiled by load
-- foo.lua
return function (i)
return i
end
end)() -- executed with call/pcall
你所要做的就是加载块并调用它,它的 return 值就是你的函数:
// load the chunk
if (luaL_loadstring(L, script)) {
return luaL_error(L, "Error loading script: %s", lua_tostring(L, -1));
}
// call the chunk (function will be on top of the stack)
if (lua_pcall(L, 0, 1, 0)) {
return luaL_error(L, "Error running chunk: %s", lua_tostring(L, -1));
}
// call the function
lua_pushinteger(L, 42); // function arg (i)
if (lua_pcall(L, 1, 1, 0)) {
return luaL_error(L, "Error calling function: %s", lua_tostring(L, -1));
}
给定一个 lua 文件,例如
-- foo.lua
return function (i)
return i
end
如何使用 C API 加载此文件并调用返回的函数?
我只需要以 luaL_loadfile
/luaL_dostring
.
一个loaded块只是一个常规函数。从C加载模块可以这样想:
return (function() -- this is the chunk compiled by load
-- foo.lua
return function (i)
return i
end
end)() -- executed with call/pcall
你所要做的就是加载块并调用它,它的 return 值就是你的函数:
// load the chunk
if (luaL_loadstring(L, script)) {
return luaL_error(L, "Error loading script: %s", lua_tostring(L, -1));
}
// call the chunk (function will be on top of the stack)
if (lua_pcall(L, 0, 1, 0)) {
return luaL_error(L, "Error running chunk: %s", lua_tostring(L, -1));
}
// call the function
lua_pushinteger(L, 42); // function arg (i)
if (lua_pcall(L, 1, 1, 0)) {
return luaL_error(L, "Error calling function: %s", lua_tostring(L, -1));
}