【问题标题】:Lua argument as string nameLua 参数作为字符串名称
【发布时间】:2011-10-25 14:10:33
【问题描述】:

我有一个这样的字符串:

local tempStr = "abcd"

我想将名为“abcd”的变量发送到这样的函数:

local abcd = 3

print( tempStr ) -- not correct!!

结果将是 3,而不是 abcd。

【问题讨论】:

    标签: string lua arguments


    【解决方案1】:

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

    local tempStr = "abcd"
    
    local t = {}
    
    t[tempStr] = 3
    
    print( t[tempStr]) -- will print 3
    

    【讨论】:

      【解决方案2】:

      对于声明为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 声明为本地,则不能这样做。

      【讨论】:

      • 最后一句不应该是“如果你将abcd声明为本地,你就不能这样做”?
      【解决方案3】:

      函数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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 2015-09-17
        • 1970-01-01
        • 1970-01-01
        • 2015-05-15
        • 1970-01-01
        相关资源
        最近更新 更多