Uiy
Uiy

Reputation: 165

lua modify arrays inside function

I am trying to modify a collection of arrays inside of a variadic function. I end up working on a copy when trying to add to the arrays and they get lost after the call. Is there any way to pass values by ref in Lua?

function myfunc(...)
local args = {...}
--do work on args--
end

"do work" doesn't actually end up doing anything but it works outside the function just fine.

Obviously I could pass an array of arrays and not use ... but that kinda defeats the purpose of using ...

Upvotes: 0

Views: 1369

Answers (2)

kikito
kikito

Reputation: 52668

The purpose of using ... is grouping the whole parameter list in one varible. That has little to do with the by-reference or by-value nature of the parameters.

All natural types in Lua are passed by value, with tables being the only exception.

The simplest way to do what you want is to pass an array of arrays. If the two extra characters seem like too much typing, know that you can remove the parenthesis instead:

foo({a,b,c})
foo{a,b,c} -- equivalent

Upvotes: 0

jpjacobs
jpjacobs

Reputation: 9549

In Lua, you can't just choose to pass variables by reference or not. Basic types are never passed by reference (like numbers and booleans), others are always passed by reference (like tables, userdata and strings). In the case of strings this does not matter much, because they are immutable anyhow.

So either you pass your arguments you want to work on globally as strings like this:

a=2
b=3
function myfunc(...)
   local args={...}
   for k,v in pairs(args) do
       _G[v]=_G[v]+k
   end
end
myfunc('a')
print(a) -- 3
myfunc('a','b')
print(a,b) -- 4    5

Note that this only works on globals, since locals are not kept in a table.

Working with tables makes this kind of things less painful:

function myfunc(t)
    for k,v in pairs(t) do
           t[k]=v+k
    end
end
tab1={a=2}
myfunc(tab1)
print(tab1.a) -- 3
tab2={a=2,b=3}
myfunc(tab2)
print(tab2.a,tab2.b) -- 3    5

Upvotes: 3

Related Questions