【问题标题】:Lua: Executing a string and storing the output of the command in a variableLua:执行字符串并将命令的输出存储在变量中
【发布时间】:2014-11-09 03:24:33
【问题描述】:

我有一个 Lua 脚本,它接收字符串中的函数调用。我需要执行该调用并将输出作为变量中的字符串检索,以便稍后将其发送到某个地方。

例如,我将收到字符串"json.encode('{1:1, 2:3, 5:8}')"。我想执行它并获得一个值为ret = json.encode('{1:1, 2:3, 5:8}')的变量。

我尝试过以多种不同方式使用 loadstring,包括我 found in the docs 的方式,但我无法让它按我的意愿工作:

    > s = "json.encode('{1:1, 2:3, 5:8}')"
    > ret = assert(loadstring(s))()
    > print(ret)
    nil

我知道字符串正在执行,因为如果我设置 s = print(json.encode('{1:1, 2:3, 5:8}')) 我会看到输出。我只是不知道如何在变量中获取输出。

谢谢!

【问题讨论】:

    标签: string variables lua output execute


    【解决方案1】:

    我刚刚找到了一种方法来做我想做的事,但我仍然想知道你们是否能找到任何缺陷/更好的方法来做到这一点,因为我对 Lua 还很陌生:

        > s = "json.encode('{1:1, 2:3, 5:8}')"
        > s2 = "return("..s..")"
        > ret = assert(loadstring(s2))()
        > print(ret)
        "{1:1, 2:3, 5:8}"
    

    【讨论】:

      【解决方案2】:

      您需要从加载的块中返回值。因为你告诉 lua 你不关心返回的值,所以它把它扔掉了。

      注意:我没有方便的 json 模块,因此我将函数替换为仅返回其参数的函数以用于演示目的:

      > json = { encode = function(s) return s end }
      > s = "json.encode('{1:1, 2:3, 5:8}')"
      > ret = assert(loadstring("return "..s))()
      > print(ret)
      {1:1, 2:3, 5:8}
      

      【讨论】:

      • 非常感谢!如果用户想要发送字符串a = 42 来更改先前声明的变量a=0 的值,则该返回的串联将导致错误stdin:1: [string "return(a = 84)"]:1: ')' expected near '='。你知道有什么办法可以避免吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多