虽然我不太了解 Lua,但这是一种相当意外和奇怪的行为。
假设我有 my_module.lua
:
local function dump(o) -- SO:9168058
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local mymodule = {}
function mymodule.myfunction(indict)
print(dump(indict))
end
return mymodule
好的,现在我运行这个:
lua5.3 -e "mm=require('my_module'); mm:myfunction({aa=12})"
这不应该很复杂——我“导入”了模块,并在其中调用一个函数,参数是一个对象(表/关联数组/字典 {aa=12}
) .然后我只是尝试从函数中打印这个参数。但是,我明白了:
$ lua5.3 -e "mm=require('my_module'); mm:myfunction({aa=12})"
{ ["myfunction"] = function: 0x5619aeddf770,}
因此,myfunction
中对 print(dump(indict))
的响应,其中 indict
是传递给 myfunction 的参数
,Lua 打印.... "myfunction"
????!
我什至无法理解这个 - 这怎么可能发生?
以及如何将对象作为参数传递给函数,以便当我从函数内部打印参数时,打印作为参数的对象 - 而不是函数本身??!
顺便说一句,即使我只是传递一个数字而不是一个对象,也会发生同样的情况,比如说:
lua5.3 -e "mm=require('my_module'); mm:myfunction(42)"
编辑:做了一些调试 - 所以这样:
function mymodule.myfunction(indict)
print(indict)
print(dump(indict))
end
...我在使用数字参数时得到了这个打印输出:
$ lua5.3 -e "mm=require('my_module'); mm:myfunction(42)"
table: 0x55f15a7a07a0
{ ["myfunction"] = function: 0x55f15a7a07e0,}
... 所以它在任何地方都看不到这个数字,但该函数将自己视为第一个参数。
这提醒了我,在 Python 类中,您必须将方法编写为以“self”作为第一个参数的函数,所以我尝试了这个:
function mymodule.myfunction(self, indict)
print("self", self, "indict", indict)
print(dump(indict))
end
...打印:
$ lua5.3 -e "mm=require('my_module'); mm:myfunction(42)"
self table: 0x560510b5a7d0 indict 42
42
...或者在传递对象的情况下:
$ lua5.3 -e "mm=require('my_module'); mm:myfunction({aa=12})"
self table: 0x55d51c9d5800 indict table: 0x55d51c9d5880
{ ["aa"] = 12,}
……好吧,这更像是……
谁能解释这是从哪里来的 - 为什么我需要在这种情况下添加“self”参数?
最佳答案
在 lua 中,调用 a:b(x)
将对象 a
的引用作为第一个 (self
) 参数传递给函数b
。
因为你的模块定义是:
function mymodule.myfunction(indict)
并且调用语句是mm:myfunction
,对象/表mm
作为第一个参数传递(这里是indict
) .
要么把函数定义改成
function mymodule:myfunction(indict)
如果你想像mm:myfunction
那样保持调用,或者像mm.myfunction
一样调用函数。
PiL book 中详细讨论了该行为关于 OOP 概念。
The effect of the colon is to add an extra hidden parameter in a method definition and to add an extra argument in a method call. The colon is only a syntactic facility, although a convenient one; there is nothing really new here.
关于lua - require'd 函数的参数在 Lua 中丢失/消失了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384194/