我想知道是否有一种更简单的方法来调用同一表的函数或设置变量,而不是编写表名。
例如,在下面的示例代码中,有没有更简单的方法可以从MyClass.test()
调用MyClass.setup()
函数?
local MyClass = {}
function MyClass.test()
print("Hello")
end
function MyClass.setup()
MyClass.test()
end
MyClass.setup()
答案 0 :(得分:3)
如果您使用:
而不是.
来调用函数,则Lua隐式插入对表本身的引用作为第一个参数(类似于this
指针是一些对象,面向语言)。然后您可以说self:test()
摆脱名称依赖。
local MyClass = {
test = function(self)
print("Hello")
end,
setup = function(self)
self:test()
end
}
MyClass:setup()
答案 1 :(得分:2)
您可以将模块表设置为环境:
Array
(
[1] => Array
(
[0] => Array
(
[userID] => 316
[fullName] => S J
[employeeSupervisiorID] => 1
[employeePhoto] => 1537274885.jpg
[childern] => Array
(
[0] => Array
(
[userID] => 336
[fullName] => S G
[employeeSupervisiorID] => 316
[employeePhoto] => 1537274919.jpg
[childern] => Array
(
[0] => Array
(
[userID] => 423
[fullName] => Test User
[employeeSupervisiorID] => 336
[employeePhoto] => 1537275091.jpg
)
)
)
[1] => Array
(
[userID] => 337
[fullName] => R K
[employeeSupervisiorID] => 316
[employeePhoto] => 1537274940.jpg
[childern] => Array
(
[0] => Array
(
[userID] => 418
[fullName] => J D
[employeeSupervisiorID] => 337
[employeePhoto] => 1537274978.jpg
)
)
)
[2] => Array
(
[userID] => 420
[fullName] => A S
[employeeSupervisiorID] => 316
[employeePhoto] => 1537274997.jpg
)
)
)
[1] => Array
(
[userID] => 405
[fullName] => De B
[employeeSupervisiorID] => 1
[employeePhoto] => 1537274961.jpg
[childern] =>
)
[2] => Array
(
[userID] => 421
[fullName] => Sanjay j
[employeeSupervisiorID] => 1
[employeePhoto] => 1537275044.png
[childern] =>
)
)
)
答案 2 :(得分:1)
local MyClass = {}
function MyClass:Setup()
print('hello...Setup')
end
function MyClass:Test()
self:Setup() -- self -> MyClass
print('hello...Test')
end
MyClass:Test()
-- or inherit
local newClass = MyClass
newClass:Test()
答案 3 :(得分:1)
local MyClass = {}
function MyClass.test()
print("Hello")
end
function MyClass.setup(self)
self.test()
end
MyClass.setup(MyClass)
密钥是self
。在状态下,MyClass
是obj,由{}
创建,因此您可以使用MyClass.Test(MyClass)
传入参数MyClass
来使用{{1 }} obj。
ps :
Lua提供的语法糖:
MyClass.setup(MyClass)==> MyClass:setup()