Reputation: 147
I have a problem with basic module usage in Lua. I have one file "helloworld.lua" and a second file "main.lua". I would like to call a function from the first file inside the second file. But I am getting an error:
attempt to call field 'printText' (a nil value)
My actual code is below. Can someone tell me where the problem is?
helloworld.lua
local module = {}
function module.printText()
print("Hello world")
end
return module
main.lua
hello = require("helloworld")
hello.printText()
Upvotes: 1
Views: 72
Reputation: 29214
As mentioned in the comments, this is the right way to do it. This could be a problem if there is a conflicting helloworld
module, or if you have a running lua state and are modifying the files without starting a new one.
require
will only load the module passed with a string once. Check package.loaded["helloworld"]
. You can set this to nil so that require will load the file again:
package.loaded["helloworld"] = nil
hello = require("helloworld") -- will load it for sure
Upvotes: 1