1

I need to create many variables, and I want to do declare these variable's name by function. In like this:

function DefineVariable(VariableName)
return VariableName = 123 end

What i want from the function is:

DefineVariable(weg423)
-- Result: weg423 = 123

But it was not easy as I thought... That function does not worked. I want to know how to turn it into working function.

And, could i receive an answer about this too?

a = "blahblah"

...somehow...

DefineVarByValue(a)
-- Result: blahblah = 123

Ah and one more question. how to change 'table variable' to 'string or number variable'? (i mean the 'number expected, got table' error...)

1 Answer 1

1

All simple types in Lua are passed by value, so your DefineVariable function gets the current value of the variable weg423 and not the name of it, which means you can't change the value of weg423 from the function.

If this is a global variable, then you can pass the name of that variable (for example, DefineVariable('weg423')) and the function can then change the value of that variable by referencing it as a key in _G or _ENV table (_G[VariableName] = whatever).

I still don't see a point in doing it this way. There is nothing wrong with using weg423 = 123.

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

5 Comments

For example: 1. io.open("someCode.lua", r) 2. string.match(find "DoDeclare(...VarName...)") 3. VarName = 123 4. ??? 5. profit! // This is what i am trying now. So i thought i need that function
I just wanted to solve this question(stackoverflow.com/questions/32923823)
I mean, I want to find all the string "Portal(...VarName...)" in file by io thing, then declaring all the founded VarNames. it's not that good way but atleast it can solve that question's problem, I guess. these 2 answers aren't solved the real problem. Only solved is about the print() code. but techniqally, b is already declared when you print a. so... yes. thats it.
You can't really "declare" variables with dynamic names, nor that you need to. The SO question you referenced provides several answers, so I'm not sure what you need beyond what's already answered there. What exactly are you trying to do with those variables you harvested from the file?
...Woah. I just find an answer. It was just right there in your question. (_G[VariableName] = whatever) This one. lol I thought 'what thw hell is this? w/e It must be some advanced function that i can't understand' until now. Well, thanks. if you just write that as form as a function... :)

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.