2012-02-18 15 views
0

輸出爲下面的腳本是:如何使用Lua中的數字鍵值引用表?

AD[1] = [variable not found] 
AD['2'] = bar 

如何修改功能getfield命令返回一個值v對於這兩種情況?

function getfield (f) 
    local v = _G  
    for w in string.gfind(f, "[%w_]+") do 
    v = v[w] 
    end 
return v 
end 

AD = {[1] = 'foo', ['2'] = 'bar'} 
data = {"AD[1]","AD['2']"} 

for i,line in ipairs(data) do 
    s = getfield(line) 
    if s then 
     print(line .. " = " .. s) 
    else 
    print(line .. " = [variable not found]") 
    end 
end 

UPDATE: 我90%肯定,這是要爲我工作:

function getfield (f) 
    local v = _G  
    for w in string.gfind(f, "['%w_]+") do 
     if (string.find(w,"['%a_]")==nil) then 
     w = loadstring('return '..w)() 
     else 
     w = string.gsub(w, "'", "") 
     end 
     v=v[w] 
    end 
    return v 
end 

回答

1

出現這種情況的工作

function getfield (f) 
    local v = _G  
    for w in string.gfind(f, "['%w_]+") do 
    local x = loadstring('return '..w)() 
    print(w,x) 
    v = v[x] or v[w] 
    end 
return v 
end 

AD = {[1] = 'foo', ['2'] = 'bar'} 
data = {"AD[1]","AD['2']"} 

for i,line in ipairs(data) do 
    s = getfield(line) 
    if s then 
     print(line .. " = " .. s) 
    else 
    print(line .. " = [variable not found]") 
    end 
end 

,但它是相當脆弱的。

請注意,我在模式中添加了'

難點在於有時w是一個表示名稱(鍵)的字符串,有時候它是一個表示數字的字符串。在第二種情況下,它需要從字符串轉換爲數字。但是你需要上下文或一些語法來決定。

這裏是我的意思是那種脆弱的:

>  data = {"math[pi]","AD['2']"} 
>  
>  for i,line in ipairs(data) do 
>>  s = getfield(line) 
>>  if s then 
>>    print(line .. " = " .. s) 
>>  else 
>>   print(line .. " = [variable not found]") 
>>  end 
>>  end 
math table: 0x10ee05100 
pi nil 
math[pi] = 3.1415926535898 
AD table: 0x10ee19ee0 
'2' 2 
AD['2'] = bar 


> pi = 3 
> math[3] = 42 
>  data = {"math[pi]","AD['2']"}> 
>  for i,line in ipairs(data) do 
>>  s = getfield(line) 
>>  if s then 
>>    print(line .. " = " .. s) 
>>  else 
>>   print(line .. " = [variable not found]") 
>>  end 
>>  end 
math table: 0x10ee05100 
pi 3 
math[pi] = 42 
AD table: 0x10ee19ee0 
'2' 2 
AD['2'] = bar 

math[pi]是不變的,但getfield解釋在全球範圍內的PI,並得到3所以返回的math錯誤的領域。

+0

什麼會使它失敗? – shaun5 2012-02-18 03:52:46

+0

請參閱附錄「我認爲那種脆弱性......」 – 2012-02-18 04:08:40

+0

我無法想出讓它失敗的場景。我想:AD = {[1] ='foo',['1'] ='foobar',['2'] ='bar'}會這樣做,但仍然有效。 – shaun5 2012-02-18 04:12:28

0

你會得到的字符串'1'"'2'"。你必須評估它把它變成它是什麼對象:

v = v[loadstring('return ' .. w)()] 

不這樣做,如果該字符串從不受信任的來源了過來(如用戶輸入或東西),因爲它們可以執行任意代碼。

+0

當我用代碼替換v = v [w]時出現錯誤... – shaun5 2012-02-18 03:23:24

+0

@ shaun5,錯誤是? – 2012-02-18 03:43:51

+0

嘗試索引本地'v'(一個零值) – shaun5 2012-02-18 03:45:55

相關問題