将一个函数存储在一个模块中

我正在创建一个对象的原型,我想让构造函数接受一个参数,使对象可以从外部模块获取一个函数。这是我的代码。我将在下面进一步解释我的问题。

对象原型:

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   <---- 这里是错误
    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引用它分配给的表。

点赞
用户3735873
用户3735873

我认为这是你想做的:

main.lua

m = require 'module'

m:new('foo')
m:f()

foo.lua

local function foo(self)
  print('Inside foo')
end

return foo

module.lua

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
2015-02-07 14:38:45
用户3735873
用户3735873

这是一种不同的方法,可能更接近你想要的。

main.lua

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()     --再次调用 A 来验证两个不同的对象是否存在

foo.lua

local function foo(self)
  print('Inside foo '..self.title)
  for k,v in pairs(self.dat) do
    print(k,v)
  end
end

return foo

module.lua

local m = {}

function m:new(moduleString, title, table)
    self = {}
    self.title = title or ''            --默认为空
    self.dat = table or {}              --可选表数据
    self.f = require( moduleString )
    return self                         --返回对象引用
end

return m
2015-02-09 16:48:49