【问题标题】:Create local variables programmatically (in Lua)以编程方式创建局部变量(在 Lua 中)
【发布时间】:2021-08-08 01:49:16
【问题描述】:

在 Lua 中使用自制的 doco 系统玩得很开心。例如

fun("abs","return abs value", function (x,y)
        return math.abs(x,y) end)

我被困在一个细节上。我想让“abs”成为本地函数。但我不知道如何以编程方式做到这一点。

当然,我可以写入某个 Lib 对象中的字段并将其命名为Lib.abs(x,y),我认为这就是我必须要做的。 但是任何聪明的 Lua 人都可以告诉我如何不这样做吗?

【问题讨论】:

    标签: lua


    【解决方案1】:

    我认为您没有太多选择,因为虽然您可以为局部变量赋值(使用 debug.setlocal 函数),但它是按索引分配的,而不是按名称分配的,因此必须存在一个本地变量变量已经具有该索引。

    我认为您将函数存储在表格字段中的建议没有任何问题。

    【讨论】:

      【解决方案2】:

      我要做的是,我会编写(甚至覆盖)_G,运行你的函数/程序,然后恢复它。

      function callSandboxed(newGlobals, func)
          local oldGlobals = {} --make a new table to store the values to be writen (to make sure we don't lose any values)
          for i,_ in pairs(newGlobals) do
              table.insert(oldGlobals, _G[i]) --Store the old values
              _G[i] = newGlobals[i] --Write the new ones
          end
          func() --Call your function/program with the new globals
          for i,v in pairs(oldGlobals) do
              _G[i] = v --Restore everything
          end
      end
      

      在这种情况下,你要做的是:

      --Paste the callSandboxed function
      
      callSandboxed({abs=math.abs},function()print(abs(-1))end) --Prints 1
      

      如果您想从 _G 中删除所有旧值(不仅是您要替换的值),那么您可以使用这个:

      function betterCallSandboxed(newGlobals, func) --There's no point deep copying now, we will replace the whole table
          local oldGlobals = _G --Make a new table to store the values to be writen (to make sure we don't lose any values)
          _G = newGlobals --Replace it with the new one
          func() --Call your function/program with the new globals
          _G = oldGlobals
      end
      

      现在如果在 funcprintmath(etc) 中为 nil。

      【讨论】:

      • 重写_G? (或者在 Lua 5+ 中,重写 _ENV)?有趣的方法。 _G=_ENV={abs=math.abs} 是否意味着全球环境中的其他一切现在都可以访问了?
      • 哦,感谢您告诉我有关 _ENV 的信息。我习惯于使用旧版本的 lua,所以我没有意识到这个新的 _ENV 东西。不过,为了兼容性,我想我会坚持使用 _G
      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2012-10-01
      相关资源
      最近更新 更多