【问题标题】:How implement the interface in lua?lua中如何实现接口?
【发布时间】: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 是否是“对象”。如果将公共模块视为单例对象是有意义的,那么使用: 是有意义的。如果没有,无论出于何种原因,使用. 可能会更好。也就是说,我不确定为什么对于这个示例用法,一个模块完全有意义。

标签: c lua


【解决方案1】:

如果您希望在多个 VM 之间共享该值,那么实现此目的的唯一方法是通过主机支持(C 端)。将 getter 和 setter 函数导出到每个 VM,它们将在 C 源代码中的相同 static int v_status 上运行。如果 Lua VM 位于不同的线程上,请使用访问同步。

模块无法解决您的任务,“通用”不会为不同的虚拟机共享。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 2010-10-10
    • 2013-06-27
    • 2020-04-30
    • 2010-10-16
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多