0
votes

I am trying to modify a Lua variable in C. I pass Lua userdata to a C function and the C function uses them and changes them. I want these values changed in Lua as well. Here's my code -

Lua -

 t = require 'coroutines'
 function foo()
      bar = 0
      foo1 = t.colorHistogram(bar)
      print(bar)
 end

C -

Here I do not know what to put. I read up how the two exchange data. Lua creates a stack that it pushes the arguments into and C accesses those args using the lua_Object. So

 int foo = lua_tonumber(L,1);
 foo = 5;

would initialize foo as 0 and set it to 5. However, the print statement in Lua still displays 0 as the value as it is not the memory where the variable "bar" in Lua is stored that is getting modified. I wanted to know if there is a way to modify the memory. I have also tried replacing the data on the stack with the modified value. That does not work either.

Any help is appreciated. Thank you.

EDIT**

I suppose I was not very clear in my original question. I tried sorry. Anyways, I'll try better -

What I basically want to do is pass a value to inline C, have C modify that value and be able to read it as modified in Lua. I do no care too much to modify that particular memory location or variable. As long as there is some way for me to read the value that C modified in Lua, I will take that.

 foo1, bar = t.colorHistogram(bar) 

will not work because "t" is a lua function call and colorHistogram is an inline C function in that Lua function. If I pass bar to t.colorHistogram, I would need the Lua function "t" to be able to return bar which would mean I would need the Lua function "t" to read bar as modified. That is what I am not sure how to do. Thanks for your response btw. END EDIT

1
nil, booleans, numbers and strings are passed by value in Lua, so as far as I can see you're effectively manipulating a copy on the stack.Joachim Isaksson
Yes I know that. That is why I said it is not the memory where the variable is located that is being modified and that is why I tried modifying the value on the stack itself. It didn't work. Thanks for your response though :)maverick1989

1 Answers

2
votes

Variables are not passed to functions; values are passed to functions. The number 0 is a value. local bar = 0; t.colorHistogram(bar); is functionally no different from t.colorHistogram(0).

You cannot manipulate the content of a parameter variable from within a Lua function, because Lua functions are not passed variables. They're passed the contents of a variable.

Note that it doesn't matter whether it's a C-function or a Lua function; this is just how Lua parameter passing works. Parameters are inputs only; if you want to modify a "variable", then it either must be a global or an output that the caller stores into that variable:

bar = 0
foo1, bar = t.colorHistogram(bar)