Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

lua

lua-api

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.


2 Answers

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.

like image 120
Oleg V. Volkov Avatar answered May 20 '26 09:05

Oleg V. Volkov


I probably wouldn't rely on it, but Lua's debug library can figure this out (by looking for the OP_SELF opcode in the bytecode). In Lua:

local t = {}
function t:f()
  print( debug.getinfo( 1, "n" ).namewhat )
end

t.f( t ) --> prints "field"
t:f()    --> prints "method"

In C you would need lua_getstack() and lua_getinfo().

like image 39
siffiejoe Avatar answered May 20 '26 11:05

siffiejoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!