我刚刚开始使用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类代码是否导致此问题?我尝试过各种各样的事情。我很确定它试图访问的自我是第一个参数,即mytable.myfunction(self,myarg)。任何想法来修复这个nil值引用。该错误实际发生在Start函数内的第二行(当self.Ready执行时)。
答案 0 :(得分:3)
function GameSystem:Run() if self:Init() then self.Thread = MOAICoroutine.new () self.Thread:run(self.Start)
我的猜测是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中,函数是函数是函数,它不是通过存储在表中以某种方式“污染”,因此引用该函数的第三方可以知道您希望将其作为方法调用某些特定的“班级实例”。