gpt4 book ai didi

c++ - 以编程方式嵌入 Lua 加载模块 (C++)

转载 作者:太空狗 更新时间:2023-10-29 20:18:18 26 4
gpt4 key购买 nike

我正在将 Lua 嵌入到 C++ 应用程序中。

我有一些模块(现在是简单的 .lua 脚本),我想在引擎启动时以编程方式加载,这样当引擎启动时,没有它们的脚本就可以使用模块必须在脚本顶部包含一个 require 'xxx'。

为了做到这一点,我需要能够以编程方式(即 C++ 结束)要求引擎加载模块,作为初始化的一部分(或之后不久)。

有人知道我该怎么做吗?

最佳答案

嗯,我只是使用简单的方法:我的 C++ 代码只是调用 Lua 的 require 函数来预加载我想要预加载的 Lua 脚本!

// funky = require ("funky")
//
lua_getfield (L, LUA_GLOBALSINDEX, "require"); // function
lua_pushstring (L, "funky"); // arg 0: module name
err = lua_pcall (L, 1, 1, 0);
// store funky module table in global var
lua_setfield (L, LUA_GLOBALSINDEX, "funky");

// ... later maybe handle a non-zero value of "err"
// (I actually use a helper function instead of lua_pcall
// that throws a C++ exception in the case of an error)

如果你有多个模块要加载,当然,把它放在一个循环中......:)

关于c++ - 以编程方式嵌入 Lua 加载模块 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4525757/

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