Lua - namespace of variables inside a module
I created a module named BaseModule
with a variable template_path
and a function get_template
using this variable:
module("BaseModule", package.seeall)
template_path = '/BASEMODULE_PATH/file.tmpl'
function get_template()
print template_path
end
Then I create another module called "ChildModule"
local BaseModule = require "BaseModule"
module("ChildModule", package.seeall)
setmetatable(ChildModule, {__index = BaseModule})
template_path = '/CHILDMODULE_PATH/file.tmpl'
some_child_specific_variable = 1
By doing setmetatable
, I want to copy all the variables and functions from BaseModule
to ChildModule
(let's say inherit from them) and add additional methods and variables to the new module.
The problem is that I am calling
ChildModule.get_template
I expect it to return , but it won't. He returns . /CHILDMODULE_PATH/file.tmpl
/BASEMODULE_PATH/file.tmpl
However, when I access ChildModule.template_path
, it contains the correct value (from ChildModule
).
What can I do to get Lua to use variables ChildModule
in a method ChildModule.get_template
, but not use variables BaseModule
(parent module)? There isn't this object in Lua, so how can I tell Lua to use the current value?
source to share
I think you are still using an outdated version of Lua. In any case, you need to set the value template_path
internally BaseModule
using some function and set template_path
in the base as local
. So, something like this:
BaseModule
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
ChildModule
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()
Since you are inheriting, you should not try to directly set the global variables of the base module.
source to share
I think you are trying to manipulate variables, whereas you probably want to manipulate the properties of the objects being created. Maybe something like this:
-- 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)
This will print:
/BASEMODULE_PATH/file.tmpl /CHILDMODULE_PATH/file.tmpl 1
as expected.
By the way, you can turn child.lua
into a one-liner:
return setmetatable({template_path = '/CHILDMODULE_PATH/file.tmpl',
some_child_specific_variable = 1}, {__index = require "base"})
Not that you did it, but you could.
source to share