簡體   English   中英

Lua 參數作為字符串名稱

[英]Lua argument as string name

我有一個這樣的字符串:

local tempStr = "abcd"

我想將名為“abcd”的變量發送到 function,如下所示:

local abcd = 3

print( tempStr ) -- not correct!!

結果將是 3,而不是 abcd。

如果您使用表而不是“普通”變量,則可以使用局部變量:

local tempStr = "abcd"

local t = {}

t[tempStr] = 3

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

你不能用聲明為local的變量來做到這一點。 這些變量只是堆棧地址; 他們沒有永久存儲。

您想要做的是使用變量的內容來訪問表的元素。 這當然可以是全局表。 為此,您將執行以下操作:

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

如果將abcd聲明為本地,則不能這樣做。

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