New to Lua, trying to figure out how to do OOP using the middleclass library
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:
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. Secondly, I changed require 'middleclass'
to require 'middleclass.init'
in both files and removed module(..., package.seeall)
. After that, the example code worked just fine on my machine with Lua 5.1.4.
main.lua
require 'Person'
local testPerson = Person:new("Sally")
testPerson:speak()
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. It is not setup to work that way. The intention is to include 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.
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
require("middleclass");
Make sure you don't have a module declaration in a file using middleclass, ie don't have a
module(...,package.seeall)
..for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.