我有使用Lua C API的C ++应用程序。 我通过lua api声明了全局表:
lua_newtable(L);
lua_pushstring(L, "someLuaFunc");
lua_pushcfunction(L, &someCFunc);
lua_settable(L, -3);
lua_setglobal(L, "table1");
现在我可以使用'来调用someLuaFunc。'或者':'
table1.someLuaFunc()
table1:someLuaFunc()
并且两个案例都将运行someCFunc。
问题是:在someCFunc中有没有办法确定它是如何被调用的(通过:或。)?
在我的情况下,检查参数计数和类型不是一个选项。
答案 0 :(得分:3)
不,你不能。
object:method()
直接翻译为
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
也就是说,SELF
操作码在寄存器上的调用对象附近安排了函数,然后CALL
操作码执行常规调用。
答案 1 :(得分:3)
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()
.