Page 2 of 2

Re: Editing a table by referencing.

Posted: Sun Sep 07, 2014 8:05 pm
by kikito
Robin wrote:The way values are passed in Lua is the same for all types, and it behaves in some ways as by value and in other ways as by reference. It's generally called call by object identity.
Thanks for this, I didn't know.
Zilarrezko wrote:Oh, wait. Could I use the C api to do what I want? LuaJIT and I think Lua have some C api in right?
I think you should stop building on top of what you have done so far. Doing things for learning is fine, but the fact that something helped the learning process doesn't make it a good foundation. It sounds like your code is asking you to stop building features and start trimming / reorganizing things instead.

Re: Editing a table by referencing.

Posted: Sun Sep 07, 2014 8:46 pm
by Plu
Let me preface this by saying you should listen to Kikito; what you're trying to do isn't really the Lua way and you'll be working against the language more than with it, which is never a good thing.

That said; there are ways. There are always ways. You can wrap an integer or string in a closure:

Code: Select all

makeNewInt = function( initial )
  local value = initial
  return function( arg )
    if arg then
      value = arg
      return arg
    else
      return value
    end
  end
end

a = makeNewInt( 6 )
a() -- 6
a( 7 ) -- 7
a() -- 7
b = a -- copies a reference to the closure
b() -- 7
b( 9 ) -- 9
a() -- now also 9
Due to all the function call overhead, the performance here is pretty poor; don't do this in time-critical code. But it does work, and for some cases might even be useful.

Re: Editing a table by referencing.

Posted: Sun Sep 07, 2014 9:42 pm
by Zilarrezko
Yeah closures was the other idea I had, but I don't like them. Alright, whatever, back to my occasional problem solving.