函數可以存儲在變量(全局和本地)和表中,可以作爲參數傳遞,並可以由其他函數返回。
當我們談論一個函數名稱,比如print時,我們實際上是在討論一個包含該函數的變量。
a = {p = print}
a.p("Hello World")
print = math.sin
a.p(print(1))
sin = a.p
sin(10, 20)
--> Hello World
-- ’print’ now refers to the sine function
--> 0.841470
-- ’sin’ now refers to the print function
--> 10 20
函數定義實際上創建型「功能」的值,並將其分配給一個變量的聲明(分配,更具體地)。 我們不僅可以將函數存儲在全局變量中,還可以存儲在表格字段和局部變量中。這樣的定義對於包來說特別有用:因爲Lua將每個塊作爲一個函數處理,所以塊可以聲明本地函數,這些函數僅在塊中可見。
-------------------------- 區別 -------------- -------------
功能監聽
local object = display.newImage("ball.png")
object.id = "ball object"
local function onObjectTouch(event)
if event.phase == "began" then
print("Touch event began on: " .. event.target.id)
end
return true
end
object:addEventListener("touch", onObjectTouch)
在功能收聽您添加事件偵聽器的對象。當touch事件以某種方式分派時,onObjectTouch 函數將被調用。
表監聽1
local object = display.newImage("ball.png")
object.id = "ball object"
local function onObjectTouch(self, event)
if event.phase == "began" then
print("Touch event began on: " .. self.id)
end
return true
end
object.touch = onObjectTouch
object:addEventListener("touch", object)
在表聆聽者1,你有一個對象(更具體甲TABLE)。您將觸摸對象添加到對象,並通過onObjectTouch值提供此關鍵字。因此,在向對象添加觸摸事件偵聽器之後,corona將在對象TABLE中搜索鍵值「touch」,這就是爲什麼您要將對象作爲第二項輸入,而不是函數(在此方法中,corona希望主表不是功能):object:addEventListener("touch", object)
。 在onObjectTouch方法中,您現在有兩個條目:self和event。自我是你的客體,事件就像往常一樣是你的觸摸事件。
表2監聽
local object = display.newImage("ball.png")
object.id = "ball object"
function object:touch(event)
if event.phase == "began" then
print("Touch event began on: " .. self.id)
end
return true
end
object:addEventListener("touch", object)
在第三種方法請關注主要區別是:在使用object.touch = onObjectTouch
我們使用object:onObjectTouch
的情況。請記住,只要你用這個結構就意味着:在這最後一種方法
object:onObjectTouch(...) ≣ onObjectTouch(self, ...)
爲此我們並不需要告訴電暈:哎電暈對象有一個名爲「接觸」與「onObjectTouch」的價值關鍵:object.touch = onObjectTouch
這裏很清楚地解釋了https://docs.coronalabs.com/api/type/EventListener/addEventListener.html –