0

Say i have two files:

One is called mainFile.lua:

function altDoFile(name)
    dofile(debug.getinfo(1).source:sub(debug.getinfo(1).source:find(".*\\")):sub(2)..name)
end

altDoFile("libs/caller.lua")

function callBack()
    print "called back"
end

doCallback()

The other called caller.lua, located in a libs folder:

function doCallback()
    print "performing call back"
    _G["callBack"]()
end

The output of running the first file is then:

"performing call back"

Then nothing more, i'm missing a line!

Why is callBack never getting executed? is this intended behavior, and how do i get around it?

The fact that the function is getting called from string is important, so that can't be changed.

UPDATE: I have tested it further, and the _G["callBack"] does resolve to a function (type()) but it still does not get called

4

3 回答 3

1

为什么不只使用dofile

似乎 的目的altDoFile是用您要调用的脚本替换正在运行的脚本的文件名,从而创建一个绝对路径。在这种情况下,路径caller.lua是相对路径,因此您无需更改任何内容即可让 Lua 加载文件。

将您的代码重构为:

dofile("libs/caller.lua")

function callBack()
    print "called back"
end

doCallback()

似乎给出了您正在寻找的结果:

$ lua mainFile.lua 
performing call back
called back

就像旁注一样,altDoFile如果路径不包含\字符,则会引发错误。Windows 使用反斜杠作为路径名,但 Linux 和 MacOS 等其他操作系统不使用。

在我的情况下,在 Linux 上运行脚本会引发错误,因为string.find返回 nill 而不是索引。

lua: mainFile.lua:2: bad argument #1 to 'sub' (number expected, got nil)

如果您需要知道主脚本的工作路径,为什么不将其作为命令行参数传递:

C:\LuaFiles> lua mainFile.lua C:/LuaFiles

然后在 Lua 中:

local working_path = arg[1] or '.'
dofile(working_path..'/libs/caller.lua')
于 2012-07-04T00:06:24.483 回答
1

如果你只是希望能够走回一个目录,你也可以修改 loader

 package.path = ";../?.lua" .. package.path; 

因此,您可以通过执行以下操作来运行您的文件:

require("caller")
于 2012-07-04T08:55:35.033 回答
-1

dofile "../Untitled/SensorLib.lua" -- 使用反向路径库

最好的问候 K。

于 2015-11-16T22:25:07.820 回答