我刚刚开始使用 MOAI,我正在尝试使用 MOAICoroutine 创建一个传统的游戏循环。问题是,当我将使用 30log 构建的“类”的一部分的函数传递给它时,它返回一个错误。它似乎可以继续运行,但我想修复该错误。我的猜测是 MOAICoroutine 使用点符号调用函数,而不是使用冒号的语法糖方法。这是代码:
class = require "30log.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)。修复这个零值引用的任何想法。该错误实际上发生在 Start 函数内的第二行(当 self.Ready 执行时)。
最佳答案
function GameSystem:Run() if self:Init() then self.Thread = MOAICoroutine.new () self.Thread:run(self.Start)
My guess is that the MOAICoroutine is calling the function using the dot notation rather than the syntactical sugar method with a colon.
如何使用点符号(或冒号符号)调用函数?句号或冒号左侧是什么?你没有向它传递一个对象,只是一个函数。它的调用者将该函数存储在表中这一事实对于它来说是完全未知的。它只是接收一个函数并调用它。
如果您希望协程以方法调用启动,请在传递给 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中,函数就是函数就是函数,它不会以某种方式通过存储在表中而被“污染”,这样引用该函数的第三方就可以知道您希望将其作为方法调用到某个特定的“类实例”。
关于lua - 尝试在 Lua 中使用 MOAICoroutine 索引本地 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586920/