【问题标题】:Lua - variables namespace inside moduleLua - 模块内的变量命名空间
【发布时间】:2013-01-21 09:52:26
【问题描述】:

我创建了一个名为 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 使用当前值?

【问题讨论】:

  • get_template 函数无法编译。我想你在发帖时忘记了括号?

标签: inheritance lua


【解决方案1】:

我认为您仍在使用已弃用的 Lua 版本。无论如何,您需要使用一些函数在BaseModule 中设置template_path 值,并将基中的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()

既然是继承,一定不要尝试直接设置base-module的全局变量。

【讨论】:

    【解决方案2】:

    我认为您正在尝试操作变量,而您可能想要操作正在创建的对象的属性。也许是这样的:

    -- base.lua
    local M = {}
    M.template_path = '/BASEMODULE_PATH/file.tmpl'
    function M:get_template()
      return self.template_path
    end
    return M
    
    -- child.lua
    local M = {}
    setmetatable(M, {__index = require "base"})
    M.template_path = '/CHILDMODULE_PATH/file.tmpl'
    M.some_child_specific_variable = 1
    return M
    
    -- main.lua
    local base = require "base"
    local child = require "child"
    
    print(base:get_template(), child:get_template(),
      child.some_child_specific_variable)
    

    这将打印:

    /BASEMODULE_PATH/file.tmpl  /CHILDMODULE_PATH/file.tmpl 1
    

    如你所料。

    顺便说一句,您可以将child.lua 变成单行:

    return setmetatable({template_path = '/CHILDMODULE_PATH/file.tmpl',
      some_child_specific_variable = 1}, {__index = require "base"})
    

    不是你应该,但你可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 2016-02-25
      • 2015-03-27
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多