我在 C++ 应用程序中嵌入 Lua。
我有一些模块(目前,简单的 .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)
Run Code Online (Sandbox Code Playgroud)
如果你有多个模块要加载,当然,把它放在一个循环中...... :)
| 归档时间: |
|
| 查看次数: |
1814 次 |
| 最近记录: |