【发布时间】:2020-05-06 07:59:55
【问题描述】:
我在编写简单的 OpenGL 演示时玩得很开心,最近我决定将 Lua 与我的 C++ 引擎一起使用,以便动态更改渲染,而不必在我的项目上重新编译。因此,我可以更轻松地调整渲染算法。但我知道我目前的渲染更新功能可能远非高效。
目前,我正在将矩阵从 C++ 传输到 Lua,在 Lua 脚本中对其进行修改并将其发送回我的 C++ 渲染引擎。但是每次我从 C++ 引擎收到更新调用时,我都会重新加载 Lua 脚本,并且我会丢失所有变量上下文。这意味着我总是从头开始,我的渲染远非顺利。我在下面包含一些代码示例来解释我在做什么。我目前正在学习带有 C++ 嵌入的 Lua,所以我知道我仍然没有最佳实践。
update.lua
function transform(m)
amplitude = 1.5
frequency = 500
phase = 0.0
r = {}
for i = 1, #m do
r[i] = {}
for j = 1, #m[i] do
if (i % 2) then
r[i][j] = amplitude * math.sin(m[i][j] + phase)
else
r[i][j] = -amplitude * math.sin(m[i][j] + phase)
end
phase = phase + 0.001
end
end
return r
end
-- called by c++
function update()
m = pull()
r = transform(m)
push(r)
end
matrix.cpp
// pull matrix from lua point of view
static int pull(lua_State * _L)
{
_push(_L, &_m);
return 1;
}
// push matrix from lua point of view
static int push(lua_State * _L)
{
// get number of arguments
int n = lua_gettop(_L);
if(1 == n) {
_pull(_L, 1, &_m);
}
return 1;
}
void matrix::load_file(char * file, char * function)
{
int status;
// load the file containing the script we are going to run
status = luaL_loadfile(_L, file);
switch (status) {
case LUA_OK:
break;
case LUA_ERRFILE:
std::cout << "LUA_ERRFILE: " << lua_error(_L) << std::endl;
break;
case LUA_ERRSYNTAX:
std::cout << "LUA_ERRSYNTAX: " << lua_error(_L) << std::endl;
break;
default:
std::cout << lua_error(_L) << std::endl;
}
lua_getglobal(_L, function);
status = lua_pcall(_L, 1, 1, 0);
if (status != LUA_OK) {
std::cout << "error running file" << lua_error(_L) << std::endl;
}
}
void matrix::update()
{
load_file("lua/update.lua", "update");
}
我在调用 update() 函数时想到了passing some arguments,但我想知道 C++ 到 Lua 然后再回到 C++ 的方法是否正确且有效。特别是考虑到我可能会在 Lua 中传输和修改巨大的矩阵。我可能缺乏一些嵌入式 Lua 知识来在加载脚本时保持上下文。你对我将如何改进我的代码有一些一般性的建议吗?我知道我目前的方法过于复杂。
【问题讨论】:
-
load_file长什么样子? -
我编辑了我的帖子以包含 load_file 函数
-
luaL_loadfile之后,为什么不直接将加载的块保存到全局变量中? -
感谢您的建议。如果我保存块,它是否也会保留全局变量并能够在以后使用它们?我想我也可以在需要 update() 函数时重新运行?我正在检查如何保存该块。