如何在Lua中实现接口?

例如,我有 a.lua、b.lua、c.lua。它们拥有许多相同的代码,并在不同的 Lua 虚拟机中运行。因此,我想要实现一个包含 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 中,我需要"common"模块

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++。 非常感谢!!!

点赞
用户3125367
用户3125367

如果您希望将值共享到多个虚拟机中,唯一的方法是通过主机支持(C端)实现。将getter和setter函数导出到每个虚拟机中,这些函数将在C源代码中操作相同的static int v_status。如果Lua虚拟机在不同的线程中,使用访问同步。

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

2014-09-25 16:11:10