我正在为对象创建一个原型,我希望构造函数能够获取一个参数,该参数允许对象从外部模块获取函数。这是我的代码。我将在下面进一步解释我的问题。
对象原型:
local obj = {}
local obj_mt = { __index = obj }
function obj.new( moduleString )
local newObj = {}
newObj:f = require( moduleString )
return setmetatable( newObj, obj_mt )
end
return obj
功能模块:
local function foo()
-- code
end
return foo
当我运行这个时,我得到一个错误,告诉我在newObj:function =之后,应该有函数参数。我没有通过require(moduleString)返回函数吗?我需要提到的另一件事是,如果我使用:
newObj.f = require( moduleString )
而不是:
newObj:f = require( moduleString )
在newObj表中存储函数没有问题,但是当我运行它时,函数不能使用self参数来引用newObj(或者构造原型时使用的任何变量名)。基本上我需要的是一个存储在外部模块中的函数,该函数可以访问使用self关键字加载时放置的父表。
编辑:以下是foo()的实际功能:
local function AIfollow( path, L, R, T, B, X, Y )
local L = L
local R = R
local T = T
local B = B
local x = self.img.x <---- Here is the error
local y = self.img.y
local xLoc = ( X - X%tileSize )/tileSize
local yLoc = ( Y - Y%tileSize )/tileSize
if( xLoc < R and xLoc > L and yLoc < T and yLoc > B ) then
local vx = self.img.x - x
local vy = self.img.y - y
local d = math.sqrt( vx*vx + vy*vy )
self.img:setLinearVelocity( vx/d*self.speed, vy/d*self.speed )
else
self.img:setLinearVelocity( path[x][y].vX*self.speed, path[x][y].vY*self.speed )
end
end
这件事的细节并不重要;我想要指出的是,在标记的行上,我得到一个错误,告诉我它正在尝试索引一个不存在的全局变量self。我不知道该怎么做是让函数AIfollow中的self引用它所分配的表。
答案 0 :(得分:3)
我认为这就是你要做的事情:
m = require 'module'
m:new('foo')
m:f()
local function foo(self)
print('Inside foo')
end
return foo
local m = {}
local m_mt = { __index = m }
function m:new( moduleString )
self.newObj = {}
self.f = require( moduleString )
return setmetatable( self.newObj, m_mt )
end
return m
答案 1 :(得分:1)
这是一种可能更接近你想要的方法。
m = require 'module'
a = m:new('foo','A',{'a','b','c'})
a:f()
b = m:new('foo','B',{'aa','bb','cc'})
b:f()
a:f() --once again call A to verify two different objects exist
local function foo(self)
print('Inside foo '..self.title)
for k,v in pairs(self.dat) do
print(k,v)
end
end
return foo
local m = {}
function m:new(moduleString, title, table)
self = {}
self.title = title or '' --none by default
self.dat = table or {} --optional table data
self.f = require( moduleString )
return self --return object reference
end
return m