我想做的是;使用模块创建两个不同且独立的表,但似乎正在发生的事情是;如果我已经使用过'要求'那么它会给我一个前一个需求的参考,我真正想要的只是模块的值/副本。我不能使用' dofile'因为1)。我需要使用相对路径和2)。我正在Corona中为Android构建这个,我理解' dofile'与.apk不兼容。
这是我的代码。
这是我的main.lua
foo = require('modules.myModule')
bar = require('modules.myModule')
bar:changeName()
assert(foo.name ~= bar.name)
这是在%cd%/ modules / myModule
中local M = {
name = "hai",
changeName = function(self)
self.name = 'not_hai'
end
}
return M
答案 0 :(得分:3)
您的模块可以返回M
而不是M
您的模块:
return
function() -- this is a constructor of M
local M = {
name = "hai",
changeName = function(self)
self.name = 'not_hai'
end
}
return M
end
你的主要剧本:
foo = require('modules.myModule')()
bar = require('modules.myModule')()
bar:changeName()
assert(foo.name ~= bar.name)
答案 1 :(得分:1)
作为变体,您可以使用此不需要的功能:
Ys
答案 2 :(得分:0)
这是我写模块的方式
local M = {}
function M.new()
local myTable = { name = "hai" }
myTable:changeName ()
self.name = 'not_hai'
end
return myTable
end
return M
用法:的
local m = require('myModule')
foo = m.new()
bar = m.new()
bar:changeName()