【发布时间】:2014-09-26 00:11:10
【问题描述】:
例如,我有 a.lua、b.lua、c.lua。它们有许多相同的代码,并且它们在不同的 lua VM 中运行。所以我想实现一个包含a,b,c相同代码的通用模块。
问题如下:
1.如果a,b,c具有相同的变量v_status,并且v_status的取值范围是确定的。例如,值为:
STAT_NULL = 1
STAT_ACTIVE = 2
STAT_INACTIVE = 3
我想我有两种方式来实现通用模块
第一种方式是:
--common.lua
local common = {}
local v_status = STAT_NULL
function common.set_status(st)
v_status = st
end
function common .get_status()
return v_status
end
return common
在 a、b、c 中,我需要“通用”模块
local common = require "common"
如果我想设置/获取状态,我可以这样做:
common.set_status(STAT_ACTIVE)
local status = common.get_status()
================================================ ====================================
第二种方式是:
local common = {}
function common:set_status(st)
self.v_status = st
end
function common:get_status()
return self.v_status
end
return common
在a、b、c中,我可以如下调用这些函数:
local common = require "common"
common:set_status(STAT_ACTIVE)
local status = common:get_status()
我想知道哪个是正确的。也许他们都错了。请告诉我正确的方法。 我是lua的新手,我想将此功能实现为lua的风格而不是c/c++。 非常感谢!!!
【问题讨论】:
-
这两个都是正确的。区别在于
common是否是“对象”。如果将公共模块视为单例对象是有意义的,那么使用:是有意义的。如果没有,无论出于何种原因,使用.可能会更好。也就是说,我不确定为什么对于这个示例用法,一个模块完全有意义。