我是新手,并尝试从子类heroClass
创建一个新的HERO CharacterClass.lua中的代码:
local CharacterClass =
{
name = " ",
hp = " ",
velocity = " ";
}
function CharacterClass:new(o, nameCharacter, hpCharacter, velocityCharacter)
local o = o or {}
setmetatable( o, self )
self.__index = self
self.name = nameCharacter
self.hp = hpCharacter
self.velocity = velocityCharacter
return o
end
-- CREATING HERO INHERIT
local heroClass = CharacterClass:new()
function heroClass:new (o, name, hp, velocity, playerId, color)
local o = o or CharacterClass:new(o, name, hp, velocity)
setmetatable(o, self)
self.__index = self
return o
end
main.lua中的代码
local CharacterClass = require( "CharacterClass" )
local heroClassMain = heroClass:new()
我运行代码
后出现此错误main.lua:45: attempt to index global 'heroClass' (a nil value) stack traceback: main.lua:45: in main chunk
PS:当我在main中创建一个新的CharacterClass时,它工作得很好,但是当我尝试创建一个新的heroClass(子类)时,我收到了错误!
任何人都知道什么是错的?谢谢!
答案 0 :(得分:1)
修改您的CharacterClass.lua
,如下所示:
local CharacterClass = {
name = " ",
hp = " ",
velocity = " ",
}
function CharacterClass:new(o, nameCharacter, hpCharacter, velocityCharacter)
-- same as before
end
-- CREATING HERO INHERIT
local heroClass = CharacterClass:new()
function heroClass:new (o, name, hp, velocity, playerId, color)
-- same as before
end
return {heroClass = heroClass, CharacterClass = CharacterClass }
现在,当你在main.lua
中使用require时,还需要做更多的工作:
local classModule = require "CharacterClass"
local CharacterClass, heroClass = classModule.CharacterClass, classModule.heroClass
local heroClassMian = heroClass:new()
以前,您的heroClass
子类未提供给main.lua
文件。这就是导致错误追溯的原因。