如何引用具有Lua中数字键值的表?

时间:2012-02-18 03:07:08

标签: 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

更新 我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

2 个答案:

答案 0 :(得分: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的错误字段。

答案 1 :(得分:0)

您将获得字符串'1'"'2'"。你必须对它进行评估,把它变成任何对象:

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

如果字符串来自不受信任的来源(如用户输入或其他内容),则不要这样做,因为它们可以执行任意代码。