Lua 类 的__index 是一个函数,如何实现继承?

How to implement inheritance for Lua classes whose __index is a function?

通过this tutorial,Lua可以通过给派生class table分配一个metatable实现继承,__index指向基础 class table,像这样:

BaseClass = {}
function BaseClass:foo()
end

DerivedClass = {}
setmetatable(DerivedClass, {__index=BaseClass}) -- set inheritance here

derived_instance = {}
setmetatable(derived_instance, {__index=DerivedClass})
derived_instance:foo() -- derived_instance can call BaseClass method foo()

但是,Lua中的面向对象也可以通过metatable __index指向一个函数来实现。这提供了更好的灵活性,但我不知道如何实现继承。此测试代码演示了我的想法,但未能 运行:

#include <juce_core/juce_core.h>
#include <lauxlib.h>
#include <lualib.h>

int BaseClass_foo( lua_State* lua )
{
    juce::Logger::writeToLog( "BaseClass_foo called" );
    return 0;
}

int BaseClass( lua_State* lua )
{
    juce::Logger::writeToLog( "BaseClass called" );
    const char* key = lua_tostring( lua, 2 );
    if ( strcmp( key, "foo" ) == 0 )
        lua_pushcfunction( lua, BaseClass_foo );
    else
        lua_pushnil( lua );
    return 1;
}

int DerivedClass( lua_State* lua )
{
    juce::Logger::writeToLog( "DerivedClass called" );
    lua_pushnil( lua );
    return 1;
}

const char* lua_src =
    "obj={}\n"
    "setmetatable(obj, {__index=DerivedClass})\n"
    "obj:foo()";

int main()
{
    lua_State* lua = luaL_newstate();
    luaL_openlibs( lua );

    lua_pushcfunction( lua, BaseClass );
    lua_setglobal( lua, "BaseClass" );
    lua_pushcfunction( lua, DerivedClass );
    lua_setglobal( lua, "DerivedClass" );

    // set inheritance by metatable on class function
    lua_getglobal( lua, "DerivedClass" );

    lua_createtable( lua, 0, 0 );
    lua_pushstring( lua, "__index" );
    lua_getglobal( lua, "BaseClass" );
    lua_settable( lua, -3 );
    
    lua_setmetatable( lua, -2 );

    // run lua code
    int load_re = luaL_loadstring( lua, lua_src );
    if ( load_re == LUA_OK )
        lua_call( lua, 0, 0 );
    else
        juce::Logger::writeToLog( "Lua source load failed with " + juce::String( load_re ) + ": " + lua_tostring( lua, -1 ) );

    lua_close( lua );
}

结果,Lua 声明了一个错误,您不能在 nil 值上调用 foo,根本不会调用 BaseClass 函数。元索引搜索链在这里被打破,不同于 table 实现的 class 系统,如果键不存在,Lua 自动搜索 BaseClass table在 DerivedClass table 中。有没有办法让 Lua 继续解释绑定到 DerivedClass 的元 table?

那么 __index 函数必须 return BaseClass.foo 如果有人索引 DerivedClass.foo.

如果 __index 是 table 你基本上是这样做的:

getmetatable(DerivedClass).__index:foo()

归结为 BaseClass:foo()

如果 __index 是一个函数,你这样做:

getmetatable(DerivedClass).__index(DerivedClass, "foo")()

因此您的 __index 函数必须 return BaseClass.foo 关键参数“foo”具有相同的效果。