How to calculate and execute the Lua code in a string in Lua

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.