main.lua:45:尝试索引全球' heroClass' (一个零值)堆栈追溯:main.lua:45:在主块中

时间:2015-04-07 09:24:42

标签: lua corona

我是新手,并尝试从子类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(子类)时,我收到了错误!

任何人都知道什么是错的?谢谢!

1 个答案:

答案 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文件。这就是导致错误追溯的原因。