Lua中迭代表并调用方法

我正在尝试迭代函数表并依次调用每个函数。 我一直得到 'attempt to access a field/method NIL value' 的错误。 其中一些错误很明显,但有些让我困惑不解。

 tests={}

function tests.test1()
    print("test1 running\n")
end

function tests.test2()
    print("test2 running\n")
end

function tests.test3()
    print("test3 running\n")
end

print(tests)

-- 为什么tests.i()或tests:i()没有起作用?
for i,x in pairs(tests) do
    print("x is")
    print(x)
    print("i is")
    print(i)

    --tests.i()  -- 尝试调用NIL值的i字段
    --tests.i(tests) -- 同上
    --tests:i() -- 尝试调用NIL值的i方法
    --tests:i(tests) -- 同上
    tests[i]() -- 成功!

    --tests.x() -- 尝试调用NIL值的x字段
    --tests.x(tests) -- 同上
    --tests:x() -- 尝试调用NIL值的x方法
    --tests[x]() -- 尝试调用NIL值的?字段
end

--所有这些都能正常工作
tests.test1(tests)
tests:test1()

tests.test2(tests)
tests:test2()

tests.test3(tests)
tests:test3()

为什么tests.i()方法没有起作用,或者tests.i(tests)是期望一个'self'参数,那么为什么tests:i()没有起作用? 最后的示例显示在循环外调用所有方法都能正常工作,这使得它更加难以理解。

点赞
用户2858170
用户2858170

tests.i()tests["i"]()的简写形式。tests:i()tests["i"](tests)的简写形式。

在你的循环中,for i, x in pairs(tests) doi在各自循环中分别为"test1""test2""test3"。所以tests[i]()解析为tests["test1"]()等,即tests.test1()

请确保你理解tests.itests["i"]的简写形式,不是tests[i]!所以在一种情况下,你用字符串"i"索引tests,而在第二种情况下,你将用变量i的值对tests进行索引,而这个值是tests的一个键之一。

在你的循环中,值是函数,所以你可以直接调用x,而不必调用tests[i]

2021-05-15 07:56:29
用户3342050
用户3342050

除非你为其指定占位符,否则在调用tests:test1()时插入的参数将被丢弃。

tests = {}
function tests.test1( a )  --  你只能使用列出的参数
    local a = a or ''
    print( 'test1运行中', a )
end

你也可以调用 x() 来执行循环中的这些函数。

-- 测试 i , 测试 i。 1, 2, 3?
for i, x in pairs( tests ) do
    print( string.format('i是 "%s"', i ) )
    print( 'x是', x )

    x()  -- 与调用 tests["i"]() 相同
end

tests:test1()

i是 "test1"

x是 function: 0x1420f20

test1运行中

test1运行中 table: 0x1421f10

2021-05-15 08:39:52