2014-07-06 37 views
3

我想添加自定義的方法來顯示物體像例如預置的方法「setFillColor」科羅娜SDK如何添加自定義方法的DisplayObject

我寫了下面的代碼,不工作;然而,它解釋了我需要的東西

function display:foo(bar) 
    print(bar) 
end 


local myRectangle = display.newRect(0, 0, 150, 50) 
myRectangle:foo("something to be printed") 

我想「foo」方法爲所有DisplayObject不僅準備好myRectangle?

+0

由於返回了「ShapeObject」,它不起作用。 – hjpotter92

+0

您是試圖添加一個方法還是用自己的方法替換現有的方法? – Schollii

+0

@Schollii我想要一個像真棒「Foo」方法的新方法:) – ahmed

回答

3

下面的示例。未經測試但應該有效。然後它將可用於所有newRect調用。你將不得不爲所有顯示器做到這一點。*調用你想,因爲我們需要劫持display.newRect呼叫使用,但是

local oldNewRect = display.newRect 

function display.newRect(...) 
    local rect = oldNewRect(...) 

    function rect:foo(str) 
     print(str) 
    end 

    return rect 
end 

-- usage 

local rect = display.newRect(0, 0, 40, 40) 
rect:foo("hello") -- prints "hello" 
+0

不行,因爲他想以字符串的參數傳遞 –

+0

是的。我展示瞭如何爲每個顯示對象構造函數添加一個函數。添加將參數作爲字符串傳遞到我上面發佈的內容的功能是微不足道的 – PersuitOfPerfection

+0

編輯以添加傳遞字符串並打印其值的功能 – PersuitOfPerfection

-1

有點複雜。這裏是如何做到這一點:

-- Store the old method 
local oldNewRect = display.newRect 

display.newRect = function(...) 
    local oDisplayObject = oldNewRect(...) 

    oDisplayObject.foo = function(oDisplayObject, sText) 
     -- Do something with the display object 
     -- Print the text passed as argument 
     print(sText) 
    end 
    return oDisplayObject 
end 

local myRectangle1 = display.newRect(0, 0, 150, 50) 
myRectangle1:foo("something to be printed") 

local myRectangle2 = display.newRect(0, 0, 150, 50) 
myRectangle2:foo("something to be printed") 
+0

@PersuitOfPerfection另一方面,[http:// codepad。 org/GTYR5Tk9)不是必需的。 – hjpotter92

+0

'...'確保函數調用的所有參數都被傳遞。冒號語法也可以工作。沒有要求arg名稱是「自我」的。 – Schollii

+0

個人喜好的問題,然後我猜。整理者明確地通過自我ims – PersuitOfPerfection

2

我不想替換庫中的任何方法,因爲這意味着每個對象創建的,不只是那些你創建,會受到影響,這可能會產生意想不到的副作用。所以我會主張創建一個函數,爲您創建的每個實例添加所需的方法。這個方法還可以作爲這個顯示對象是「你的」之一(不是由Corona創建的「後臺」之一)的簽名。例如,

function myNewCustomRect(...) 
    local obj = display.newRect(...) 
    obj.foo = function (self, a,b,c) 
     -- self is obj, although obj is an upvalue so can use directly too 
     print(self, obj, a,c,b) 
    end 
    return obj 
end 

yourRect = myNewCustomRect(0, 0, 150, 50) 
yourRect:foo(1,2,3) -- first two data printed should be same 
+0

是的,這比覆蓋電暈的顯示方法要好,但是他要求擴展顯示對象本身,這就是我在示例中顯示的內容。然而,我同意創建自己的方法來調用電暈的內部方法是最好的方法。 – PersuitOfPerfection