我还在玩lua模块,我发现了以下"有趣"的问题,这取决于你在模块中创建方法/函数的方式.请注意名为test_suite.lua的文件中的以下代码:
local mtests = {} -- public interface
function mtests:create_widget(arg1)
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
return mtests
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,无论我在调用create_widget()时传入什么,arg1总是为nil.但是,如果我将函数的定义更改为如下所示:
function mtests.create_widget(arg1) -- notice the period instead of colon
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
Run Code Online (Sandbox Code Playgroud)
然后,系统正确显示arg1.
这就是我调用方法的方法:
execute_test.lua
local x = require "test_suite"
x.create_widget(widgetname)
Run Code Online (Sandbox Code Playgroud)
你能告诉我有什么区别吗?我一直在阅读:http://lua-users.org/wiki/ModuleDefinition
但我没有遇到过任何可以解释这个问题的事.谢谢.
函数声明中的所有冒号都添加了一个隐式self参数.这只是一些语法糖.
因此,如果您正在调用它(假设您将mtests表分配给foo)foo.create_widget(bar),那么bar实际上将其分配给self,并且arg1保持未分配状态,因此nil.
foo = {}
function foo:bar(arg)
print(self)
print(arg)
end
Run Code Online (Sandbox Code Playgroud)
将其称为foo.bar("Hello")打印:
Hello
nil
Run Code Online (Sandbox Code Playgroud)
但是,将其称为foo:bar("Hello")或foo.bar(foo, "Hello")给您:
table: 0xDEADBEEF (some hex identifier)
Hello
Run Code Online (Sandbox Code Playgroud)
它基本上是staticJava,C#,C++等语言中的成员方法之间的区别.
| 归档时间: |
|
| 查看次数: |
888 次 |
| 最近记录: |