2

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++?

RBerteig
  • 41,948
  • 7
  • 88
  • 128
Congelli501
  • 2,403
  • 2
  • 27
  • 28
  • This might help: http://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value – Alex May 20 '11 at 23:45

3 Answers3

8

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.

Steve Kehlet
  • 6,156
  • 5
  • 39
  • 40
0

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>  
Scott
  • 789
  • 6
  • 7
-6

Lua is a bad language. Suffer its simplicity when you need to do something just a little complex.

Nick Sotiros
  • 2,194
  • 1
  • 22
  • 18
  • 7
    This is a bad answer. – Patronics May 16 '19 at 18:24
  • 1
    So so. Lua and Python are the modern Basic. They are very common, you can develop "quick and dirty" and pat yourself on the back... but after sometime, you realize there are enormous design pitfalls. One of the worst: some type of arguments are passed by reference, others by value. This is vey counterintuitive, nobody will convince me there are serious computer science principles advocating for it. – Massimo May 19 '20 at 20:01
  • @Massimo This is the same behaviour as in Java, and Java seems to be a pretty popular language... – op414 Oct 19 '22 at 17:52