Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify whever a lua parameter should be a copy or a reference

I'm wondering if there is a way to specify if the parameters of a lua function should be copied or just referenced. Color is an object representing a color.

For example, with this code

function editColor(col)
    col.r = 0
    print(tostring(col.r))
end

color = Color(255, 0, 0)
print(tostring(color.r))
editColor(color)
print(tostring(color.r))

Makes the output

255
0
0

So col is a "reference" to color, but this code:

function editColor(col)
    col = Color(0, 0, 0)
    print(tostring(col.r))
end

color = Color(255, 0, 0)
print(tostring(color.r))
editColor(color)
print(tostring(color.r))

Makes this output

255
0
255

So here the color is copied.

Is there a way to force a parameter to be copied or referenced? Just like the & operator in C++?

like image 217
Congelli501 Avatar asked Sep 04 '25 17:09

Congelli501


2 Answers

No, parameters in Lua are always passed by value (mirror). All variables are references however. In your second example in editColor you're overriding what the variable col refers to, but it's only for that scope. You'll need to change things around, maybe instead of passing in a variable to be reassigned, have the function return something and do your reassignment outside. Good luck.

like image 143
Steve Kehlet Avatar answered Sep 07 '25 08:09

Steve Kehlet


This will do what you want. Put the variable that you want to pass by reference into a table. You can use a table to pass anything by ref, not just a string.

-- function that you want to pass the string  
-- to byref.  
local function next_level( w )  
  w.xml = w.xml .. '<next\>'  
end  


--  Some top level function that you want to use to accumulate text
function top_level()  
      local w = {xml = '<top>'} -- This creates a table with one entry called "xml".  
                            -- You can call the entry whatever you'd like, just be  
                            -- consistant in the other functions.  
  next_level(w)  

  w.xml = w.xml .. '</top>'  
  return w.xml  
end  

--output: <top><next\></top>  
like image 36
Scott Avatar answered Sep 07 '25 09:09

Scott