简体   繁体   English

Lua - 尝试调用方法'new'(零值)

[英]Lua - attempt to call method 'new' (a nil value)

New to Lua, trying to figure out how to do OOP using the middleclass library Lua的新手,试图找出如何使用middleclass库进行OOP

main.lua: main.lua:

require 'middleclass'
require 'Person'

local testPerson = Person:new("Sally"); //causes Runtime error: attempt to call method 'new' (a nil value)
testPerson:speak();

Person.lua: Person.lua:

module(..., package.seeall)
require 'middleclass'

Person = class('Person');
function Person:initialize(name)
  self.name = name;
  print("INITIALIZE: " .. self.name);
end

function Person:speak()
  print('Hi, I am ' .. self.name ..'.')
end

Why am I getting that error? 为什么我会收到这个错误?

First of all, the semicolons at the end of lines are not necessary and probably a bad habit for writing Lua code. 首先,行末尾的分号不是必需的,可能是编写Lua代码的坏习惯。 Secondly, I changed require 'middleclass' to require 'middleclass.init' in both files and removed module(..., package.seeall) . 其次,我改变了require 'middleclass'require 'middleclass.init'在这两个文件并删除module(..., package.seeall) After that, the example code worked just fine on my machine with Lua 5.1.4. 之后,示例代码在我的机器上使用Lua 5.1.4正常工作。

main.lua main.lua

require 'Person'

local testPerson = Person:new("Sally")
testPerson:speak()

Person.lua Person.lua

require 'middleclass.init'

Person = class('Person')

function Person:initialize(name)
  self.name = name
  print("INITIALIZE: " .. self.name)
end

function Person:speak()
  print('Hi, I am ' .. self.name ..'.')
end

You may be including the middleclass.lua file directly. 您可能直接包含middleclass.lua文件。 It is not setup to work that way. 没有设置以这种方式工作。 The intention is to include middleclass/init.lua . 目的是包括middleclass / init.lua

If you use the two files exactly as shown above and layout your files as shown below this will work. 如果您完全按照上面所示使用这两个文件并按如下所示布局文件,则可以使用。

./main.lua
./Person.lua
./middleclass/init.lua
./middleclass/middleclass.lua

Answer by 'Judge' above is incorrect - there is no need to include "middleclass.init" and have the folder structure shown above. 上面的'Judge'回答不正确 - 不需要包含“middleclass.init”并且具有上面显示的文件夹结构。

As stated on the Github project wiki, you can simply download the license and 'middleclass.lua', place these files in your code directory, then simply do 如Github项目维基上所述,您只需下载许可证和'middleclass.lua',将这些文件放在您的代码目录中,然后只需执行

require("middleclass");

Make sure you don't have a module declaration in a file using middleclass, ie don't have a 确保在使用middleclass的文件中没有模块声明,即没有

module(...,package.seeall)

..for example. ..例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM