Lua:执行字符串并将命令的输出存储在变量中 [英] Lua: Executing a string and storing the output of the command in a variable

查看:501
本文介绍了Lua:执行字符串并将命令的输出存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a Lua script that receives a function call in a string. I need to execute that call and retrieve the output as a string in a variable so I can later send it somewhere.

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

For example, I will receive the string "json.encode('{1:1, 2:3, 5:8}')". I'd like to execute it and get a variable with the value ret = json.encode('{1:1, 2:3, 5:8}').

我尝试了多种方式使用loadstring,包括我

I've tried using loadstring in a bunch of different ways, including a way I found in the docs, but I can't get it to work as I want:

    > 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}')),则会看到输出.我只是不知道如何在变量中获取输出.

I know the string is being executed, because if I set s = print(json.encode('{1:1, 2:3, 5:8}')) I see the output. I just don't know how to get the output in a variable.

谢谢!

推荐答案

您需要从已加载的块中返回值.因为它是在告诉lua您不关心返回的值,所以它会将其丢弃.

You need to return the value from the loaded chunk. As it is you are telling lua you don't care about the returned value so it is throwing it away.

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

Note: I don't have the json module handy so I replaced the function with a function that just returns its argument for demonstration purposes:

> 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}

这篇关于Lua:执行字符串并将命令的输出存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆