1

I'm developing a software library for electronics projects in Lua, which is quit object oriented. My objects have properties with getters and setters, which are implemented with the __index and __newindex metamethods respectively. The problem is the __index metamethod doesn't work, while the __newindex one works fine. My binding code:

int L_LED_ctor(lua_State* L){
    Board* board = GetInstance<Board>(L, 1, MT_BOARD);
    int pin = (int)luaL_checknumber(L, 2);
    LED** uData = (LED**)lua_newuserdata(L, sizeof(LED*));
    *uData = new LED(board, pin);
    luaL_getmetatable(L, MT_LED);
    lua_setmetatable(L, -2);
    return 1;
}

//getters and setters

extern "C" void RegisterComponent(lua_State* L){
    luaL_Reg led[] = {
        {"__index", L_LED_Get},
        {"__newindex", L_LED_Set},
        {"new", L_LED_ctor},
        {"Toggle", L_LED_Toggle},
        {NULL, NULL}
    };luaL_newmetatable(L, MT_LED);
    luaL_setfuncs(L, led, 0);
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__index");
    lua_setglobal(L, "LED");
}

Now, when I execute this Lua script:

led = LED.new(board, 16)
print(led.__index)
print(led.__newindex)

I get the following output:

table: 0xe7e38
function: 0xb6c27fac

which means that the __index metamethod is a table, so it is not bound from C++. What have I done wrong in my binding code?

Dirk
  • 2,094
  • 3
  • 25
  • 28
  • You have overwritten `__index` field in your metatable with the following instruction: `lua_setfield(L, -1, "__index");`. Just remove this line with the one prior to it (`lua_pushvalue(L, -1);`). – Egor Skriptunoff Apr 12 '14 at 14:34
  • If i do that, my methods don't work anymore, as it doesn't bind the metatable anymore – Dirk Apr 12 '14 at 14:56
  • OK, I got it solved by returning my methods through __index – Dirk Apr 12 '14 at 16:42

0 Answers0