gpt4 book ai didi

lua - 从 C 调用由 lua 脚本返回的函数

转载 作者:行者123 更新时间:2023-12-01 01:57:35 24 4
gpt4 key购买 nike

给定一个像这样的lua文件

-- foo.lua
return function (i)
return i
end

如何使用 C API 加载此文件并调用返回的函数?
我只需要以 luaL_loadfile 开头的函数调用/ luaL_dostring .

最佳答案

一个 loaded chunk 只是一个常规函数。从 C 中加载模块可以这样想:

return (function()  -- this is the chunk compiled by load

-- foo.lua
return function (i)
return i
end

end)() -- executed with call/pcall

您所要做的就是加载 block 并调用它,它的返回值是您的函数:

// 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 - 从 C 调用由 lua 脚本返回的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39234488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com