尝试在Lua中使用MOAICoroutine索引本地变量'self'。

我刚开始学习MOAI,正在尝试使用MOAICoroutine创建一个传统的游戏循环。问题是当我将函数传递给使用30log构建的“class”时,它会返回一个错误。它似乎仍然工作,但我想修复这个错误。我的猜测是,MOAICoroutine正在使用点表示法调用该函数,而不是带有冒号的语法糖方法。这是代码:

class = require30log.30log”
GameSystem = class ()

function GameSystem:__init(Name, Title)
  self.Name = Name
  self.Title = Title
  self.Ready = false
end

function GameSystem:Run()
  if self:Init() then
    self.Thread = MOAICoroutine.new ()
    self.Thread:run(self.Start)
    --self:Start()
    return true
  else
    print(“Init failed.”)
    return false
  end
end

function GameSystem:Init()
  print(“Initializing Game System”)
  if not self:InitTimer() then return false end
  if not self:InitWindow(640,480) then return false end
  if not self:InitViewport() then return false end
  if not self:InitGraphics() then return false end
  if not self:InitSound() then return false end
  if not self:InitInput() then return false end
  self.Ready = true
  return true
end

function GameSystem:Start()
  print(“Starting Game System”)
  while self.Ready do
    self:UpdateTimer()
    self:UpdateGraphics()
    self:UpdateSound()
    self:UpdateInput()
    coroutine.yield()
  end
end

function GameSystem:InitTimer()
  return true
end

function GameSystem:InitWindow(width, height)
  print(“Initializing Window”)

  return true
end

function GameSystem:InitViewport()
  print(“Initializing Viewport”)

  return true
end

function GameSystem:InitGraphics()
  print(“Initializing Graphics”)
  return true
end

function GameSystem:InitSound()
  print(“Initializing Sound”)
  return true
end

function GameSystem:InitInput()
    print(“Initializing Input”)
  return true
end

function GameSystem:UpdateTimer()
    --print(“Updating Timer”)
  return true
end

function GameSystem:UpdateGraphics()
  --print(“Updating Graphics”)
  return true
end

function GameSystem:UpdateSound()
    --print(“Updating Sound”)
  return true
end

function GameSystem:UpdateInput()
  --print(“Updating Input”)
  return true
end

是30log类代码引起了这个问题吗?我尝试过各种方法。我很确定它尝试访问的self是第一个参数,即mytable.myfunction(self, myarg)。有什么想法可以修复这个nil值引用的错误。实际上,错误出现在Start函数中的第二行(while self.Ready do)。

点赞
用户501459
用户501459
function GameSystem:Run()
如果 self:Init() 返回 true,则
  self.Thread = MOAICoroutine.new ()
  self.Thread:run(self.Start)
end

我猜测 MOAICoroutine 调用该函数时使用的是点表示法,而不是冒号语法糖方法。

它将点表示法 (或冒号表示法) 用于调用函数吗?在点或冒号的左边会有什么?您没有传递对象,只传递了函数。它完全不知道调用者正在将该函数存储在表中。它只接收一个函数并调用它。

如果您想让协程以方法调用的方式启动,请在传递给 coroutine.start 的函数中执行该操作:

self.Thread = MOAICoroutine.new ()
self.Thread:run(function() self:Start() end)

关键点是:

function GameSystem:Start()
end

与以下三种形式完全等价:

function GameSystem.Start(self)
end
GameSystem.Start = function(self)
end
function Foobar(self)
end

GameSystem.Start = Foobar

如果我调用:

print(Foobar)
print(GameSystem.Start)
print(someGameSystemInstance.Start)

print 将收到相同的值。在 Lua 中,函数就是函数,不会因被存储在 table 中而被 "感染",以便第三方拥有对该函数的引用时可以知道您希望它作为某个特定 'class instance' 的方法调用。

2013-01-29 16:20:07