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

后端 未结 2 573
时光说笑
时光说笑 2021-01-25 22:50

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.

2条回答
  •  醉话见心
    2021-01-25 23:43

    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}
    

提交回复
热议问题