How to compute and execute the LUA code in a string in Lua

Source: Internet
Author: User
Tags lua

This article, which introduces the LUA approach to computing, executing the LUA code in a string, is similar to the Eval function in JavaScript and can be implemented in Lua, and the friends who need it can refer to the

A, Lua execution string

There is a problem during the run, I have a string, is a mathematical expression, how to calculate the value of this string expression?

For example, local param = "7*100", I need the result is actually 700, but how to calculate this value directly? The method is as follows

Prefix the string with a "return"

Then LoadString gets a function later.

Then perform a return value of 700, so that by converting, the results are as follows:

Second, the implementation of the LUA code as a string

Sometimes we want to be able to dynamically switch contexts in our code and change the process of processing the program, at which point we need to generate some code in accordance with our own will, at which point we need to execute some LUA code from the string

In our project I hope that I can get down from the server A can execute the LUA code, use this code to update the project resources, so as to avoid whether it is the first chicken or egg problem

Copy code 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.