Lua insert multiple variables into a table

限于喜欢 提交于 2019-12-24 14:53:06

问题


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

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


回答1:


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

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




回答2:


The select function operates on the vararg ...

function b(...)
  for i = 1, select('#',...) do
    myTable[#myTable+1] = select(i,...)
  end
end

E.g.,

> myTable = {'a','b'}
> b('c','d')
> for i = 1, #myTable do print(myTable[i]) end
a
b
c
d
> 


来源:https://stackoverflow.com/questions/13214926/lua-insert-multiple-variables-into-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!