Require LUA files using a standard relative path approach - problems with: attempt to call global 'myfunc' (a nil value)

StackOverflow https://stackoverflow.com/questions/23430230

  •  14-07-2023
  •  | 
  •  

Question

I need to call a LUA function, defined in another my .lua file; from another. So, what I want is the classic C/C++ include approach. I tried with the following:

(file funcs.lua)
function myfunc(arg1, arg2)
 ..dosomething
end

and

(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
require "funcs"
myfunc(1, 2)

The require works good, but at execution I get this error:

attempt to call global 'myfunc' (a nil value)

How come? Thanks in advance,

Was it helpful?

Solution

Thank you all for the comments; I'm running LUA under OpenResty/Nginx.

I solved by exporting directly the function(s), I don't know if this is the preferred method, but I noticed that is used by lots of newer LUA modules. For example, I changed the code as follows:

file (funcs.lua)
local A = {}
function A.myfunc(arg1, arg2)
 ..dosomething
end
return A

(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
funcs = require "funcs"
funcs.myfunc(1, 2)

This works good and it's nice to have every function to be manually exported, in a sort of OOP-style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top