Lua C API如何确定函数被称为类成员还是只是从表中执行函数?

时间:2015-12-14 11:35:56

标签: c++ c lua lua-api

我有使用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中有没有办法确定它是如何被调用的(通过:或。)?

在我的情况下,检查参数计数和类型不是一个选项。

2 个答案:

答案 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操作码执行常规调用。

在这种情况下,Lua的范例是鸭子打字。这里没有明显的类型,只有table(或userinfo),所以只需检查你的参数是否有你想要处理/调用的必要数据/方法,如果它没有,那就拒绝。

答案 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().