3

If I have a variable name("x" for example) stored in another variable (varname in this example) I can create a global variable via

_G[varname]=42

This is a complicated way to say

x=42

Now I want to do the same thing for local variables. Is it possible?

2 Answers 2

11

No, because local variables are not stored in a table, or in any structure which associates their name to them. When the lua code is compiled into bytecode, local variable names turn into numeric offsets on the lua stack.

Sign up to request clarification or add additional context in comments.

Comments

3

If you really need to use a string to modify local variables, your best option is using a local table.

local localVars = {}

function setValue(varname, value)
  localVars[varname] = value
end

function getValue(varname)
  return localVars[varname]
end

You are not really creating and destroying local variables this way, but you get pretty close.

1 Comment

If you want local variables per function, then you should give each function its own local localVars = {}; with the way it is now, local variables are shared across all functions, and they persist between function calls. Also, as it is now, if you call a function which uses localVars['a'] and that function then calls a function which uses localVars['a'], the second function will clobber the first's value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.