Lua reference function from inside table inside the table (Using "self"inside of table)

标签 lua lua-table

假设我有一个表 A 和其中的函数 C 和 B,我可以通过引用自身来调用函数 C 中的表 A 函数 B 吗?

A = {
    B = function()
        print("I am B")
    end,
    C = function()
        print("I am C\nand")
        __self.B();
    end,
}
A.C();

感谢您的宝贵时间。

最佳答案

是的,使用 : 方法调用。

A:C()

: 等同于 A.C(A),但它更安全(将确切的表引用作为第一个参数传递)。

由于您在表构造函数表达式中定义 A.C 方法,因此您不能使用此语法:

function table:prop

您必须声明 self 特征(在您的代码中用作 __self)作为函数的第一个参数。

A = {
    B = function()
        print("I am B")
    end,

    C = function(__self)
        print("I am C\nand")
        __self.B();
    end
};

如果您不想将 __self 指定为第一个参数,请在分配 A 之后定义 A.C,使用以下特殊函数语法:

function A:C()
    print("I am C\nand");
    self.B();
end

这使得第一个参数成为self

关于Lua reference function from inside table inside the table (Using "self"inside of table),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40109340/

相关文章:

c - Lua C 扩展 : how to set metatable on new library

lua - 为什么 lua require 不会搜索当前目录?

c - 从 C 访问 Lua 子表字段

lua - 如何获得 Lua 表中的最大整数?

lua - Too many captures in String.match Error [帮助]

c - Lua 用户数据 : Unable to have simultaneous array access and methods

c# - 仅在 Lua 中调试范例?

lua:检索表中的键列表

function - 为什么清除传递的表在函数作用域内不起作用?

Lua 错误尝试索引全局 nil 值