如何定义以函数命名的变量? [英] How to define variable that named by function?

查看:139
本文介绍了如何定义以函数命名的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建许多变量,并且想通过函数声明这些变量的名称.像这样:

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

我想要的功能是:

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

推荐答案

Lua中的所有简单类型都是按值传递的,因此您的DefineVariable函数将获取变量weg423的当前值,而不是其名称,这意味着您无法通过该功能更改weg423的值.

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.

如果这是一个全局变量,则可以传递该变量的 name (例如DefineVariable('weg423')),然后函数可以通过将该变量引用为一个变量来更改该变量的值.键入_G_ENV表(_G[VariableName] = whatever).

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

我仍然看不到这样做的意义.使用weg423 = 123没什么问题.

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

这篇关于如何定义以函数命名的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆