gpt4 book ai didi

inheritance - Lua - 模块内的变量命名空间

转载 作者:行者123 更新时间:2023-12-02 00:13:12 25 4
gpt4 key购买 nike

我创建了一个名为 BaseModule 的模块,其中包含变量 template_path 和使用此变量的函数 get_template:

module("BaseModule", package.seeall)
template_path = '/BASEMODULE_PATH/file.tmpl'
function get_template()
print template_path
end

然后我创建另一个名为“ChildModule”的模块

local BaseModule = require "BaseModule"
module("ChildModule", package.seeall)
setmetatable(ChildModule, {__index = BaseModule})
template_path = '/CHILDMODULE_PATH/file.tmpl'
some_child_specific_variable = 1

通过执行 setmetatable,我想将所有变量和函数从 BaseModule 复制到 ChildModule(假设继承它们) 并向新模块添加一些额外的方法和变量。

问题是我打电话的时候

ChildModule.get_template

我希望它返回 /CHILDMODULE_PATH/file.tmpl 但没有返回。它返回 /BASEMODULE_PATH/file.tmpl

但是,当我访问 ChildModule.template_path 时,它包含正确的值(来自 ChildModule)。

如何让 Lua 在 ChildModule.get_template 方法中使用 ChildModule 变量而不使用 BaseModule (父模块)变量? Lua 中没有this 对象,那么如何告诉 Lua 使用当前值?

最佳答案

我认为您仍在使用已弃用的 Lua 版本。无论如何,您需要使用一些函数在 BaseModule 中设置 template_path 值,并将 base 中的 template_path 设置为 local 。所以,像这样:

基础模块

module("BaseModule", package.seeall)
local template_path = "/BASEMODULE_PATH/file.tmpl"
function get_template()
print(template_path)
end
function set_template( sLine )
template_path = sLine
end

子模块

local BaseModule = require "BaseModule"
module("ChildModule", package.seeall)
setmetatable(ChildModule, {__index = BaseModule})
ChildModule.set_template( "/CHILDMODULE_PATH/file.tmpl" )
some_child_specific_variable = 1
ChildModule.get_template()

由于您正在继承,因此您绝不能尝试直接设置基本模块的全局变量。

关于inheritance - Lua - 模块内的变量命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com