Lua - attempt to call the new method (nil value)

New in Lua, trying to figure out how to do OOP using 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 this error?

+4
source share
2 answers

First of all, semicolons at the end of lines are not needed and are probably a bad habit to write Lua code. Secondly, I changed require 'middleclass' to require 'middleclass.init' in both files and deleted module(..., package.seeall) . After that, the sample code worked 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 can include the middleclass.lua file directly. He is not determined to work like that. The goal is to include the middle class /init.lua.

If you use two files exactly as shown above and place your files as shown below, this will work.

 ./main.lua ./Person.lua ./middleclass/init.lua ./middleclass/middleclass.lua 
+5
source

The answer “Judge” above is incorrect - there is no need to include “middleclass.init” and have the folder structure shown above.

As stated on the Github wiki, you can simply download the license and "middleclass.lua", put these files in your code directory, and then just do

 require("middleclass"); 

Make sure you don't have a module declaration in the file using middleclass, i.e. doesn't have

 module(...,package.seeall) 

.. eg.

+1
source

Source: https://habr.com/ru/post/1346963/


All Articles