Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can Lua';是否需要函数返回多个结果?_Lua - Fatal编程技术网

Can Lua';是否需要函数返回多个结果?

Can Lua';是否需要函数返回多个结果?,lua,Lua,可以创建一个Lua模块,该模块通过require函数返回多个结果?我目前正在编写package.loaders的扩展,我想知道是否需要支持这种行为 例如,以以下名为mod.lua的模块为例: print("module loading") return "string1", "string2" 这是以下脚本所必需的: print("running script") s1, s2 = require("mod") print("s1: " .. tostring(s1)) print("s2:

可以创建一个Lua模块,该模块通过require函数返回多个结果?我目前正在编写package.loaders的扩展,我想知道是否需要支持这种行为

例如,以以下名为
mod.lua
的模块为例:

print("module loading")
return "string1", "string2"
这是以下脚本所必需的:

print("running script")
s1, s2 = require("mod")
print("s1: " .. tostring(s1))
print("s2: " .. tostring(s2))
结果如下:

running script
module loading
s1: string1
s2: nil
当我期望返回第二个字符串时。我不想使用这种行为,我意识到您可以通过返回一个表并解包来复制它,我只是想知道它是否有效(因为它是有效的Lua语法),我在任何地方都找不到关于这一点的明确答案。

Lua 5.1.3

require
lua导出在
loadlib.c
文件的
static int ll_require(lua_State*L)
中实现。此函数始终返回1作为堆栈上返回值的数目。

您始终可以从模块返回一个函数,并让该函数返回多个值,如下所示:

福卢阿

return function() return "abc", 123 end
巴鲁

local a, b = require "foo" ()

有时,根据您需要返回的内容,最好返回一个“表”if条目


---->Parent.Lua-->--

---->Parent.Lua-->--

=======

The favourite toy is Lego
List ALL toys on the child's favourites list:-
1       Lego
2       Meccano

如果需要的话,甚至可以使用“unpack”命令。

是的,从源代码来看,它看起来是这样的(我使用的是Lua5.2,它是相同的单一返回值)。我猜这一限制部分是因为它将结果存储在
\u LOADED[“mod”]
中,并且如果不将多个值打包到一个表中并再次解包,它将无法从中返回多个值,这在大多数情况下是不必要的。@GooseSerbus这也是因为
require
修改了返回值。如果模块返回
nil
require
返回
true
local ChildReturns=require("Child");
print("The favourite toy is "..ChildReturns.GetFavourieToy());
print("List ALL toys on the child's favourites list:-");
for F_vK,F_vV in ipairs(ChildReturns) do
    print(F_vK,F_vV);
end
The favourite toy is Lego
List ALL toys on the child's favourites list:-
1       Lego
2       Meccano