gpt4 book ai didi

lua - 为什么 Lua 的 arg 表不是单索引的?

转载 作者:行者123 更新时间:2023-12-02 00:14:51 28 4
gpt4 key购买 nike

在 Lua 命令行中,当我将参数传递给这样的脚本时:

lua myscript.lua a b c d

我可以从全局 arg 表中读取脚本的名称和参数。 arg[0] 包含脚本名称,arg[1] - arg[#arg] 包含其余参数。这个表的奇怪之处在于它在索引 0 处有一个值,这与从 1 开始索引的所有其他 Lua 数组不同。这意味着当像这样迭代它时:

for i,v in ipairs(arg) do print(i, v) end

输出仅考虑索引 1-4,不打印脚本名称。此外,#arg 的计算结果为 4,而不是 5。

这个决定有什么充分的理由吗?最初让我大吃一惊,我不得不确认手册没有弄错。

最佳答案

为什么做出某些设计决策总是很棘手,因为只有语言的创造者才能真正回答。我想选择它是为了让您可以使用 ipairs 遍历参数,而不必处理第一个特殊参数,因为它是脚本名称而不是参数。

#arg 无论如何都是没有意义的,因为它只计算连续数组部分中元素的数量,但第零索引和负索引存储在 hashmap 部分中。要获取元素的实际数量,请使用

local n = 0
for _ in pairs(arg) do
n = n + 1
end

至少在 Programming in Lua 中有记载:

A main script can retrieve its arguments in the global variable arg. In a call like

prompt> lua script a b c

lua creates the table arg with all the command-line arguments, before running the script. The script name goes into index 0; its first argument (a in the example), goes to index 1, and so on. Eventual options go to negative indices, as they appear before the script. For instance, in the call

prompt> lua -e "sin=math.sin" script a b

lua collects the arguments as follows:

arg[-3] = "lua"
arg[-2] = "-e"
arg[-1] = "sin=math.sin"
arg[0] = "script"
arg[1] = "a"
arg[2] = "b"

More often than not, the script only uses the positive indices (arg[1] and arg[2], in the example).

关于lua - 为什么 Lua 的 arg 表不是单索引的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790377/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com