我正在编写C代码来判断和修改lua中的 struct 成员,我使用元表
它适用于简单的定义,但在数组中我不能使其工作,我有以下代码
struct pinfo {
int time;
bool hide_name;
int type_info[10];
};
struct mystruct {
int id;
int value;
int option[20];
struct pinfo pf[5];
....
};
int Get_mystruct(lua_State *L) {
struct mystruct *ms = (struct mystruct*)lua_touserdata(L, 1);
lua_pushlightuserdata(L, ms);
luaL_getmetatable(L, "mystruct");
lua_setmetatable(L, -2);
return 1;
}
int mystruct_index(lua_State *L) {
struct mystruct *ms = (struct mystruct*)lua_touserdata(L, 1);
const char *field = lua_tostring(L, 2);
if (strcmp(field, "id") == 0) {
lua_pushinteger(L, ms->id);
}
else if (strcmp(field, "value") == 0) {
lua_pushinteger(L, ms->value);
}
else if (strcmp(field, "option") == 0) {
lua_pushinteger(L, ms->option[lua_tointeger(L, 3)]);
}
else {
lua_pushnil(L);
}
return 1;
}
int mystruct_newindex(lua_State *L) {
struct mystruct *ms = (struct mystruct*)lua_touserdata(L, 1);
const char *field = lua_tostring(L, 2);
int value = (int)lua_tointeger(L, 3);
if (strcmp(field, "id") == 0) {
ms->id = value;
}
else if (strcmp(field, "value") == 0) {
ms->value = value;
}
else if (strcmp(field, "option") == 0) {
ms->option[lua_tointeger(L, 3)] = (int)lua_tointeger(L, 4);
} else {
lua_pushnil(L);
}
return 0;
}
void mystruct_create(lua_State *L) {
luaL_Reg mystructData[] = {
{ "GetMyStruct", Get_mystruct},
{ "__index", mystruct_index},
{ "__newindex", mystruct_newindex},
{NULL, NULL}
};
luaL_newmetatable(L, "mystruct");
luaL_setfuncs(L, mystructData, 0);
lua_setfield(L, -2, "MyStructLua");
}
在Lua中,我的用法如下
local ms = MyStructLua.GetMyStruct(my_ptr)
print(ms.id) // Returns 0, not defined
ms.id = 1000
print(ms.id) // Returns 1000, has been defined
现在,当我go 定义数组时,例如,当我try 时出现问题
for o = 0, 19 do
mp.option[o] = 1
end
当我设置该值时,出现错误bad argument #3 to 'index' (number expected, got no value)
我想知道如何在这个元表中使用简单和复杂的数组,我有struct,它是mystruct的成员数组,我如何将它添加到_newindex和_index中