[英]how to create and call lua function, that is in multiple files, from c++
[英]how to have lua call a c++ function that returns multiple values to lua
我的代碼(部分)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 正確通信,C 函數必須使用以下協議,該協議定義了參數和結果的傳遞方式:C 函數在其堆棧中以直接順序接收來自 Lua 的參數(第一個參數首先被壓入)。 因此,當函數啟動時, lua_gettop(L) 返回函數接收到的參數數量。 第一個參數(如果有)在索引 1 處,它的最后一個參數在索引 lua_gettop(L) 處。 要將值返回給 Lua,C 函數只是將它們按直接順序(首先壓入第一個結果)壓入堆棧,並在 C 中返回結果的數量。 Lua 將正確丟棄結果下方堆棧中的任何其他值。 和 Lua 函數一樣,Lua 調用的 C 函數也可以返回很多結果。
例如,以下函數接收可變數量的數字參數並返回它們的平均值和總和:
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 */ }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.