Lua将多个变量插入表中 [英] Lua insert multiple variables into a table

查看:141
本文介绍了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将多个变量插入表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆