使用标准的相对路径方法需要LUA文件-问题:尝试调用全局"myfunc"(nil值) [英] Require LUA files using a standard relative path approach - problems with: attempt to call global 'myfunc' (a nil value)
问题描述
我需要调用另一个我的.lua文件中定义的LUA函数;从另一个.因此,我想要的是经典的C/C ++包含方法. 我尝试了以下方法:
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
和
(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
require "funcs"
myfunc(1, 2)
require工作正常,但是在执行时出现此错误:
The require works good, but at execution I get this error:
attempt to call global 'myfunc' (a nil value)
为什么? 预先感谢,
推荐答案
谢谢大家的评论;我正在OpenResty/Nginx下运行LUA.
Thank you all for the comments; I'm running LUA under OpenResty/Nginx.
我通过直接导出函数来解决问题,我不知道这是否是首选方法,但是我注意到许多新的LUA模块都使用了该方法. 例如,我将代码更改如下:
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)
这很好用,并且可以以一种OOP风格手动导出每个功能.
This works good and it's nice to have every function to be manually exported, in a sort of OOP-style.
这篇关于使用标准的相对路径方法需要LUA文件-问题:尝试调用全局"myfunc"(nil值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!