I've created a module called BaseModule with variable template_path and 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 variables and functions from BaseModule to ChildModule (let's say inherit them) and add some extra methods and variables to a new module.
The problem is when I call
ChildModule.get_template
I expect it to return /CHILDMODULE_PATH/file.tmpl but doesn't. It returns /BASEMODULE_PATH/file.tmpl.
However when I access ChildModule.template_path it contains the correct value (from ChildModule).
What can I do to make Lua use ChildModule variables in ChildModule.get_template method but not to use BaseModule (parent module) variables? There's no this object in Lua so how can I tell Lua to use a current value?
I think you're still using the deprecated version of Lua. Anyways, you need to set the template_path value inside the BaseModule using some function, and set the template_path in the base to be local. So, something like this:
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()
Since you're inheriting, you must not try to set global variables of base-module directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With