I have the following code in Lua:
ABC:
test (X)
The test function is implemented in C + +. My problem is this: I need to know what the variable name passed as parameter (in this case X). In C + + only have access to the value of this variable, but I must know her name.
Help please
Functions are not passed variables; they are passed values. Variables are just locations that store values.
When you say
Xsomewhere in your Lua code, that means to get the value from the variableX(note: it’s actually more complicated than that, but I won’t get into that here).So when you say
test(X), you’re saying, “Get the value from the variableXand pass that value as the first parameter to the functiontest.”What it seems like you want to do is change the contents of
X, right? You want to have thetestfunction modifyXin some way. Well, you can’t really do that directly in Lua. Nor should you.See, in Lua, you can return values from functions. And you can return multiple values. Even from C++ code, you can return multiple values. So whatever it is you wanted to store in
Xcan just be returned:This way, the caller of the function decides what to do with the value, not the function itself. If the caller wants to modify the variable, that’s fine. If the caller wants to stick it somewhere else, that’s also fine. Your function should not care one way or the other.
Also, this allows the user to do things like
test(5). Here, there is no variable; you just pass a value directly. That’s one reason why functions cannot modify the “variable” that is passed; because it doesn’t have to be a variable. Only values are passed, so the user could simply pass a literal value rather than one stored in a variable.In short: you can’t do it, and you shouldn’t want to.