Lua将多个变量插入表中

编程入门 行业动态 更新时间:2024-10-12 08:19:42
本文介绍了Lua将多个变量插入表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题是如何(或是否)可以在lua表中插入两个值.

My question is how (or if) you can insert two values into a lua table.

我有个返回(可变数量的值)的函数

I got a function that returns (a variable number of values)

function a(x, y) return x, y end

和另一个将点插入表中的函数

and another function that inserts that points into a table,

function b(x, y) table.insert(myTable, x, y) end

那么我该如何使用可变数量的参数调用函数b并将它们全部插入到我的表中呢?

So how can i make, that i can call function b with a variable number of arguments and insert them all into my table?

推荐答案

如果函数的最后一个参数是...(称为vararg函数),则Lua解释器会将所有多余的参数放入....您可以使用{...}将其转换为表,然后将键/值复制到名为myTable的全局表中.这是您的函数外观:

If the last parameter for your function is ... (called a vararg function), the Lua interpreter will place any extra arguments into .... You can convert it to a table using {...} and copy the keys/values into your global table named myTable. Here's what your function would look like:

function b(...) for k, v in pairs({...}) do myTable[k] = v end end b(1, 2) -- {[1] = 1, [2] = 2} is added to myTable

您应该根据要替换,合并还是将元素添加到myTable来调整功能.

You should tweak the function depending on whether you want to replace, merge or append elements into myTable.

更多推荐

Lua将多个变量插入表中

本文发布于:2023-07-15 10:44:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   变量   Lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!