我打算用C語言實現一個函數,並且這個函數將被Lua腳本調用。如何使用作爲參數傳遞給lua C函數的表?
這個函數應該接收一個lua表作爲參數,所以我應該讀取表中的字段。我嘗試像下面這樣做,但是當我運行它時,我的函數崩潰。任何人都可以幫助我找到問題嗎?
/*
function findImage(options)
imagePath = options.imagePath
fuzzy = options.fuzzy
ignoreColor = options.ignoreColor;
end
Call Example:
findImage {imagePath="/var/image.png", fuzzy=0.5, ignoreColor=0xffffff}
*/
// implement the function by C language
static int findImgProxy(lua_State *L)
{
luaL_checktype(L, 1, LUA_TTABLE);
lua_getfield(L, -1, "imagePath");
if (!lua_isstring(L, -1)) {
error();
}
const char * imagePath = lua_tostring(L, -2);
lua_pop(L, 1);
lua_getfield(L, -1, "fuzzy");
if (!lua_isnumber(L, -1)) {
error();
}
float fuzzy = lua_tonumber(L, -2);
lua_getfield(L, -1, "ignoreColor");
if (!lua_isnumber(L, -2)) {
error();
}
float ignoreColor = lua_tonumber(L, -2);
...
return 1;
}
如何從C到Lua中返回一個表:
struct Point {
int x, y;
}
typedef Point Point;
static int returnImageProxy(lua_State *L)
{
Point points[3] = {{11, 12}, {21, 22}, {31, 32}};
lua_newtable(L);
for (int i = 0; i 3; i++) {
lua_newtable(L);
lua_pushnumber(L, points[i].x);
lua_rawseti(L, -2, 0);
lua_pushnumber(L, points[i].y);
lua_rawseti(L, -2, 1);
lua_settable(L,-3);
}
return 1; // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
}
「*有問題*」*有什麼錯?你期望它做什麼,它在做什麼是不正確的? –
我想在C函數中讀取lua表,但它崩潰了,我仍然在發現問題。所以我希望有人可以幫助我檢查我使用的方式是否正確。 – Suge