gpt4 book ai didi

c++ - 如何让lua调用一个返回多个值给lua的c++函数

转载 作者:行者123 更新时间:2023-12-04 14:47:32 33 4
gpt4 key购买 nike

我的代码(部分)C++:

lua_register(L, "GetPosition", lua_GetPosition);

int lua_GetPosition(lua_State* L)
{
Entity e = static_cast<Entity>(lua_tointeger(L, 1));
TransformComponent* trans = TransformComponentPool.GetComponentByEntity(e);
if (trans != nullptr)
{
lua_pushnumber(L, trans->transform->position.x);
lua_pushnumber(L, trans->transform->position.y);
lua_pushnumber(L, trans->transform->position.z);
}
else
{
lua_pushnumber(L, 0);
lua_pushnumber(L,0);
lua_pushnumber(L, 0);
LOG_ERROR("Transform not found");
}
return 1;
}

卢阿:

local x = 69
local y = 69
local z = 69
x,y,z = GetPosition(e)
print("xyz =",x,y,z)

我期望“xyz = 1.0 1.0 1.0”我得到“xyz = 1.0 nil nil”

执行此操作的正确方法是什么,以便 lua 看到所有返回值?

最佳答案

当 Lua 调用你的函数时,它会检查它的返回值以找出它应该从堆栈中获取多少个值。在您的例子中是 1。否则 Lua 怎么知道你想要返回多少推送值?

来自 Lua 5.4 Reference Manual 4.6 Functions and Types :

In order to communicate properly with Lua, a C function must use thefollowing protocol, which defines the way parameters and results arepassed: a C function receives its arguments from Lua in its stack indirect order (the first argument is pushed first). So, when thefunction starts, lua_gettop(L) returns the number of argumentsreceived by the function. The first argument (if any) is at index 1and its last argument is at index lua_gettop(L). To return values toLua, a C function just pushes them onto the stack, in direct order(the first result is pushed first), andreturns in C the number ofresults. Any other value in the stack below the results will beproperly discarded by Lua. Like a Lua function, a C function called byLua can also return many results.

As an example, the following function receives a variable number ofnumeric arguments and returns their average and their sum:

 static int foo (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number sum = 0.0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushliteral(L, "incorrect argument");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n); /* first result */
lua_pushnumber(L, sum); /* second result */
return 2; /* number of results */
}

关于c++ - 如何让lua调用一个返回多个值给lua的c++函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69747056/

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