【发布时间】:2020-04-29 10:08:40
【问题描述】:
我正在 Lua 中构建一个类,其中包含许多相关函数组,但我不确定是否有更好的方法来构建它。我目前必须为 Lua 5.1 环境进行开发,但希望 Lua 5.3 在不久的将来成为可能。
该类将在许多不同的 Lua 程序中使用,所以我想要一些可以作为单个代码块放入的东西(我正在编程的环境意味着模块和 require 不是也不会) t 是一个选项)。
理想情况下,我想要一段黑盒代码(公开的公共方法除外),而不是在不同的类中重复代码(以提高可维护性)。
我目前拥有的是(概括的):
function Fclass()
--here I declare a bunch of local functions that can be called by any of the public methods
local function A(parms)
end
--Public methods set 1
--here I declare a bunch of state variables shared by BSelector and GetB
local BSelector = function()
A(parmvalues)
--returns a bunch of iup controls with supporting (complicated) logic
end
local GetB = function()
--returns the values of the iup controls created in Bselector
end
--Public methods set 2
--here I declare a bunch of state variables shared by DSelector and GetD
local DSelector = function()
--returns a bunch of iup controls with supporting (complicated) logic
end
local GetD = function()
A(parmvalues)
--returns the value of the iup controls created in Dselector
end
return{BSelector =BSelector , GetB =GetB, DSelector =DSelector , GetD =GetD}
end
“B”和“D”组方法是完全独立的,除了它们都使用局部函数“A”等(不依赖于外部变量);理想情况下,它们的状态变量应该组本地。
这是一个合理的结构吗?或者我应该将“B”和“D”组分成两个单独的类,然后复制本地函数或将它们作为单独的代码放入?我真的不想在类之外公开本地函数,因为不可避免地会出现命名冲突......大多数程序将使用所有方法组,尽管有些程序只使用一个组。
或者有更好的方法吗?
我这样调用它们:
myB = Fclass()
myD = Fclass()
someresults = myB.Bselector()
otherresults = myD.Dselector()
更新添加:我被告知我可能没有正确使用术语,我正在做的不是课程。我的方法基于Programming in Lua 并被选中是因为我想保留班级的状态变量?目的?私有的——只能通过公共方法访问。
【问题讨论】:
-
它们是方法的函数吗?它们应该如何执行:
f()或x:f()? -
@EgorSkriptunoff 查看帖子末尾的编辑 -- 谢谢。
-
答案将基于意见,但 FWIW,我认为您正在做的是定义类的好方法。
-
@ColeValleyGirl:“不要在不同的类中重复代码”我不明白这一点。您在 Lua 环境中工作,因此受到限制,您甚至无法使用
require模块或(显然?)做任何类似的事情(例如dofile、loadstring或类似的),这样您就可以构建自己的模块界面。那么您将如何避免代码重复?您必须为需要使用它的每个文件复制此类的源代码。 -
myB.Bselector()好的:Bselector究竟应该如何知道它被用于myB而不是myD?