寻求从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 :(得分: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