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

以下是脚本的输出内容:

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

我如何修改函数 getfield,使其能够为两种情况下的变量返回值?

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

原文链接 https://stackoverflow.com/questions/9338151

点赞
stackoverflow用户726361
stackoverflow用户726361

你会得到字符串'1'"'2'"。你需要对它进行评估,将其转换为任何对象:

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

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

2012-02-18 03:11:19
stackoverflow用户33252
stackoverflow用户33252

这个例子可以正常工作

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 的错误字段。

2012-02-18 03:48:39