albertodemichelis / squirrel

Official repository for the programming language Squirrel
http://www.squirrel-lang.org
MIT License
895 stars 149 forks source link

Function parameters as true references/pointers #232

Open oomek opened 3 years ago

oomek commented 3 years ago

Will the proper pointer/reference functionality come some day to Squirrel? I know there are workarounds like wrapping parameters in a table, but that does not work in all usage scenarios and it's a bit messy.

function func( inst1, inst2 )
{
    inst1 = inst2
    inst2 = SomeClass()
}
oomek commented 3 years ago

You would just skip the copy by defining a function or a class like in C++

function func( &inst1, &inst2 )

That would help a lot.

zeromus commented 3 years ago

Who's gonna break the bad news to him?

oomek commented 3 years ago

That means no then, would you care to explain why?

zeromus commented 3 years ago

Because there are no time machines available to go back to the day squirrel was written and add that feature at the point where planning for it would need to commence

oomek commented 3 years ago

Tried getstackinfos(2) but I see it also makes a copy, even for nested tables. Oh well it's a shame that when you aim for the simplicity the functionality has to suffer.

RizzoRat commented 3 years ago

EVERY squirrel object internally is basically a class instance. Putting something on the stack (by passing it to a function, for example) will and must copy it in all cases. Now, depending on the variable type the value stored inside this "virtual" instance is absolute (integer, for example) or already a reference (instance or table, for example). This is always the same in all cases. So it's simply type depending if a variable is a reference or not. If you have a reference and want a copy, use the clone instruction. If you have an absolute value and want a reference, encapsulate in an instance, table or array. That's not only true for passing variables to function, but simply always. Just that passing it to functions has the most obvious "effect".

However, you may also want to have a look "Free Variables", being something along a workaround (well, not really, but sometimes handy)