2012-07-07 42 views
0

尋找一些訪問Corona OOP類以外的變量的幫助。下面是裸機代碼:在Corona的OOP中,從外部訪問類的變量

module(..., package.seeall) 

local widget = require "widget" 

picker = {} 
picker.__index = picker 

function picker.new() 
local picker_object = {} 
setmetatable(picker_object,picker) 

picker_object.theHour = 12 
picker_object.theMin = 0 
picker_object.am = true 

return picker_object 
end 

function picker:getHour() 
return self.theHour 
end 

function picker:getMin() 
return self.theMin 
end 

自我是回來爲無當我嘗試從類的外部調用getHour和getMin。我應該用什麼語法來返回我的theHour和theMin變量? 謝謝!

回答

0

我試過你的代碼,沒有什麼問題。問題可能在於你訪問這個模塊的方式。這裏是我的main.lua與您的代碼工作(我要去猜你的文件名爲picker.lua):

local picker = require "picker" 
local picker_obj = picker.picker.new() 
       -- the first picker is the module (picker.lua) 
         -- the second is the picker class in the file 
print("minute: " .. picker_obj:getMin()) 
print("hour: " .. picker_obj:getHour()) 

此外,該模塊(...,package.seeall)命令已被棄用,看到this blog post for a better way to make your module.如果您使用此方法來創建你的模塊,還自稱文件picker.lua,前兩行中我main.lua將變爲:

local picker = require "picker" 
local picker_obj = picker.new() 

下面是我修改代碼以使用最簡單的方法創建模塊的新方法。只有開始和結束的變化,一切都保持不變:

-- got rid of module(), made picker local 
local picker = {} 
picker.__index = picker 

... -- all the functions stay the same 

return picker 
+0

謝謝你的回答白蘭度!有趣。唉,貶抑!我只是更新了一個更新版本的Corona,並花了半個小時瀏覽我的應用程序,拿出了widget .view的東西並修復了類似的錯誤!我有點不清楚如何改變我的課程,以適應新的方法 - 我不需要picker .__ index = picker嗎? picker_object呢?我非常努力,所以我很害怕我要打破它! :) – 2012-07-08 02:01:36

+0

對於OOP,您仍然需要picker .__ index = picker和picker_object。我更新了答案以顯示如何爲模塊使用新方法。你可以改變你的功能,更像博客文章描述的,但你不必。你有什麼工作,只要確保你添加的私有函數是本地的而不是類的成員,所以:local function foo() – brando 2012-07-09 00:47:45