module - 在模块中存储单个函数

标签 module lua require self

我正在为一个对象创建一个原型(prototype),我希望构造函数接受一个参数,该参数允许该对象从外部模块获取函数。这是我的代码。我将在下面进一步解释我的问题。

对象原型(prototype):

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 (或构造原型(prototype)时使用的任何变量名称)。所以基本上我需要的是一个存储在外部模块中的函数,该函数可以在使用 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 引用它分配到的表。

最佳答案

我认为这就是您想要做的:

main.lua

m = require 'module'

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

foo.lua

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

return foo

模块.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

关于module - 在模块中存储单个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28382513/

相关文章:

javascript - 将 module.factory 注入(inject) angularjs 中另一个模块的最佳方法

python - 如何检查模块是否可用于导入?

Lua指定库

Ruby 要求和 self.require

node.js - 找出 Node 中哪个文件需要另一个文件

ruby - 我可以 "retroactively"从模块添加类方法(在已经包含该模块之后)吗?

javascript - 将变量传递给 vuejs 模块

performance - 在我的速度测试中,Lua 表哈希索引比数组索引更快。为什么?

function - 如何在Lua中的函数内调用函数?

lua - 循环浏览不同的文件位置选项