How to calculate and execute the Lua code in a string in Lua
This article describes how to calculate and execute the Lua code in a string in Lua. Similar to the eval function in JavaScript, it can also be implemented in Lua. For more information, see
1. Execution string in Lua
There is a problem in the running process. I have a string that is a mathematical expression. How can I calculate the value of this string expression?
For example, for local param = "7*100", the result I need is actually 700. But how can I calculate this value directly? The method is as follows:
Add "return" before the string"
After loadstring, obtain a function.
Then, execute the following command to obtain the 700 return value. The conversion result is as follows:
2. Execute Lua code in string form
Sometimes, we want to dynamically switch the context in the Code and change the process of processing the program. At this time, we need to generate some code according to our own will. At this time, we need to execute some Lua code from the string.
In our project, I hope that I can get a executable lua code from the server and use this code to update the project resources, so as to avoid the problem of having chicken or eggs first.
Copy the Code as follows:
-- Defining a string to use as function later
FuncStr = "print ('test ')"
-- Running it directly
Loadstring (funcStr )()
-- Defining a function from the string and running it
Func = loadstring (funcStr)
Func ()