Lua: Executing a string and storing the output of the command in a variable

余生长醉 提交于 2019-12-02 10:10:53

问题


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.

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}').

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

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.

Thanks!


回答1:


I just found a way to do what I wanted, but I'd still like to know if you guys can find any flaw/better way to do it, since I'm very new to 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:


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.

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}


来源:https://stackoverflow.com/questions/25850797/lua-executing-a-string-and-storing-the-output-of-the-command-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!