Skip to content

Instantly share code, notes, and snippets.

@snakevil
Created April 7, 2017 03:31
Show Gist options
  • Save snakevil/85ba503df657de6c4bcdd07de2653ba5 to your computer and use it in GitHub Desktop.
Save snakevil/85ba503df657de6c4bcdd07de2653ba5 to your computer and use it in GitHub Desktop.
Lua 面向对象式开发的 __tostring 问题

Lua 面向对象式开发的 __tostring 问题

LuaJIT-2.0.4 为止tostring() 函数都只会检查并调用元表__tostring 函数。那么在面向对象式开发时,如何让基类定义地统一 __tostring 机制生效?

print(setmetatable({
    __tostring = function ( self )
        return '3'
    end
}, setmetatable({
    __tostring = function ( self )
        return '2'
    end
}, {
    __tostring = function ( self )
        return '1'
    end
})))

在上面的案例中,输出内容是 2。如果将该函数定义删除,输出内容就变成了 table: 0x01c773b8 这样的值。

转以面向对象的思维来理解,3 是类的实例,2 是类,1 是父类。

因此为了能够使用本基类统一的 __tostring 方法,在定义每个派生类时,都需要显性地定义派生类中的方法,使其能逐层递归调用至基类。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment