微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

lua – table.unpack()只返回第一个元素

参见英文答案 > Lua unpack() messing arguments1个
有人可以向我解释为什么table.unpack()只有在table.unpack()之后的函数调用中使用其他参数时才会返回第一个表元素吗?

这是一些演示代码

local a = {1,2,3,4,5}
print("Test",table.unpack(a))   -- prints "Test 1 2 3 4 5"
print(table.unpack(a),"Test")   -- prints "1 Test"

我不明白为什么第二行只打印1个Test.我希望它打印1 2 3 4 5测试.有人可以解释这种行为吗?我也有兴趣如何打第二次打印1 2 3 4 5测试.

解决方法

table.unpack返回多个值.在这种情况下定义的行为是,如果它不是表达式列表中的最后一个,那么将丢弃除第一个返回值之外的所有值.

book

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement,Lua discards all of its results. When we use a call as an expression,Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

作为一种解决方法,您可以将其余参数附加到表中,并使表成为最后一个参数.

原文地址:https://www.jb51.cc/lua/274574.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐