提问人:eugene_prg 提问时间:1/21/2013 最后编辑:prapineugene_prg 更新时间:1/22/2013 访问量:1522
Lua - 模块内的变量命名空间
Lua - variables namespace inside module
问:
我使用这个变量创建了一个名为 with variable and function 的模块: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
通过这样做,我想将所有变量和函数从 to(假设继承它们)并向新模块添加一些额外的方法和变量。setmetatable
BaseModule
ChildModule
问题是当我打电话时
ChildModule.get_template
我希望它返回 /CHILDMODULE_PATH/file.tmpl
,但没有。它返回 /BASEMODULE_PATH/file.tmpl
。
但是,当我访问它时,它包含正确的值(从 )。ChildModule.template_path
ChildModule
我该怎么做才能让Lua在方法中使用变量,但不使用(父模块)变量?Lua 中没有这个对象,那么我如何告诉 Lua 使用当前值?ChildModule
ChildModule.get_template
BaseModule
答:
3赞
hjpotter92
1/21/2013
#1
我认为您仍在使用已弃用的 Lua 版本。无论如何,您需要在 using some 函数中设置值,并将 in the base 设置为 。所以,像这样的东西:template_path
BaseModule
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 的全局变量。
0赞
Paul Kulchenko
1/22/2013
#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"})
不是你应该这样做,但你可以。
评论
get_template