Search code examples
c++clualua-api

Lua C API How to determine were function called as class member or just function from table?


I have C++ application which uses Lua C API. I declared global table via lua api:

lua_newtable(L);

lua_pushstring(L, "someLuaFunc");
lua_pushcfunction(L, &someCFunc);
lua_settable(L, -3);

lua_setglobal(L, "table1");

and now I can call someLuaFunc using '.' or ':'

table1.someLuaFunc()
table1:someLuaFunc()

and both cases will run someCFunc.

Question is: is there any way, inside someCFunc, to determine how it was called (via : or .)?

Checking argument count and types is not an option in my case.


Solution

  • No, you can't.

    object:method()
    

    is directly translated to

    main <123.lua:0,0> (4 instructions, 16 bytes at 00020510)
    0+ params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions
            1       [1]     GETGLOBAL       0 -1    ; object
            2       [1]     SELF            0 0 -2  ; "method"
            3       [1]     CALL            0 2 1
    

    That is, SELF opcode aranges function right near calling object on registers and then CALL opcode performs regular call.

    Lua's paradigm in this case is duck typing. There's no distinct type, just table (or userinfo) anyway, so just check if your argument have necessary data/methods you want to process/call and reject if it doesn't.