简体   繁体   English

Lua 参数作为字符串名称

[英]Lua argument as string name

I have a string like this:我有一个这样的字符串:

local tempStr = "abcd"

and I want to send the variable which is named as "abcd" to a function like this:我想将名为“abcd”的变量发送到 function,如下所示:

local abcd = 3

print( tempStr ) -- not correct!!

and the result will be 3, not abcd.结果将是 3,而不是 abcd。

You can do it with local variables if you use a table instead of a "plain" variable:如果您使用表而不是“普通”变量,则可以使用局部变量:

local tempStr = "abcd"

local t = {}

t[tempStr] = 3

print( t[tempStr]) -- will print 3

You can't do that with variables declared as local .你不能用声明为local的变量来做到这一点。 Such variables are just stack addresses;这些变量只是堆栈地址; they don't have permanent storage.他们没有永久存储。

What you're wanting to do is use the content of a variable to access an element of a table.您想要做的是使用变量的内容来访问表的元素。 Which can of course be the global table.这当然可以是全局表。 To do that, you would do:为此,您将执行以下操作:

local tempStr = "abcd"
abcd = 3 --Sets a value in the global table.
print(_G[tempStr]) --Access the global table and print the value.

You cannot do that if you declare abcd as local.如果将abcd声明为本地,则不能这样做。

The function debug.getlocal could help you. function debug.getlocal可以帮助您。

function f(name)
    local index = 1
    while true do
        local name_,value = debug.getlocal(2,index)
        if not name_ then break end
        if name_ == name then return value end
        index = index + 1
    end 
end

function g()
    local a = "a!"
    local b = "b!"
    local c = "c!"
    print (f("b")) -- will print "b!"
end

g()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM