找到你要的答案

Q:How to define variable that named by function?

Q:如何定义由函数命名的变量?

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...)

我需要创建许多变量,并且我想按函数声明这些变量的名称。在这样:

function DefineVariable(VariableName)
return VariableName = 123 end

我想要的功能是:

DefineVariable(weg423)
-- Result: weg423 = 123

但它并不容易,因为我认为…该函数不工作。我想知道如何把它变成工作函数。

而且,我能得到关于这个的答案吗?

a = "blahblah"

...somehow...

DefineVarByValue(a)
-- Result: blahblah = 123

啊还有一个问题。如何更改“表变量”到“字符串或数字变量”?(我的意思是“预期的数字,得到表”错误…)

answer1: 回答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.

在Lua的所有简单类型是按值传递的,所以你的definevariable功能得到变量的当前值weg423而不是它的名字,这意味着你不能改变weg423的功能价值。

如果这是一个全局变量,那么你可以通过该变量的名称(例如,definevariable('weg423 '))和功能可以改变该变量的值引用它作为一个重点在_g或_env表(_g [名] =什么)。

我仍然没有看到这样做的一点。使用有什么错weg423 = 123。

lua