How to get reference to variable within a function?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
ddabrahim
Party member
Posts: 201
Joined: Mon May 17, 2021 8:05 pm
Contact:

How to get reference to variable within a function?

Post by ddabrahim »

Hi everyone.

So I have an interesting problem to solve.
I would like to modify a local variable inside a function
This is what I would like to do:

Code: Select all

local a = 10

print(a) -->>output 10

myFunction = function(_value)
	_value = _value + 1
end

myfunction(a)

print(a) -->> output 11
I prefer not to make the variable global and not to work with the actual variable name within the function. Instead I would like to work with just a reference to a variable so I can pass any variable to the function to work with.

I was searching the Lua documentations and the web but could not find any solution.

One thing that was repeatedly come up in searches is to use a C module to use pointers to get a reference to the variable in memory but no info was shared how to do that exactly and I don't have a lot of experience with C.

So I was wondering, is there anything like a pointer in Lua to pass a variable by reference to a function or could someone recommend a library to work with memory addresses of variables to get around this?

I would appreciate any help.

Thank you.
User avatar
pgimeno
Party member
Posts: 3674
Joined: Sun Oct 18, 2015 2:58 pm

Re: How to get reference to variable within a function?

Post by pgimeno »

Not possible.

There are two ways around it:

1) Return the value and assign it:

Code: Select all

function inc(x)
  return x + 1
end

a = 5
a = inc(a)
print(a) -- prints 6
2) Use a table:

Code: Select all

obj = {}
obj.a = 5

function inc_a(t)
  t.a = t.a + 1
end

inc_a(obj)

print(obj.a) -- prints 6
Edit: Or this variant:

Code: Select all

function inc(t)
  t[1] = t[1]+ 1
end

a = {5}

inc(a)

print(a[1]) -- prints 6
User avatar
ddabrahim
Party member
Posts: 201
Joined: Mon May 17, 2021 8:05 pm
Contact:

Re: How to get reference to variable within a function?

Post by ddabrahim »

Thanks a lot.

Using a table works nicely. I can even pass the variable name as a string. So then I can make the function work with any variable.
This is what I do.

Code: Select all

obj = {}
obj.a = 10

myFunction = function(_t,_n)
    _t[_n] = _t[_n] + 1
end

myFunction(obj, "a")

print(obj.a) -- output 11
I am happy with it.
Thanks :)
Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests