简体   繁体   中英

How can programs make Lua(or python) interpreter execute statements provided by the program?

I am using Cent OS 7.

I want to write a program(written in Java or other languages) that can interact with Lua interpreter. I hope that my program can feed statements to Lua interpreter, and get executed real-time, while previous variables are still available.

For example, my program feeds a = 4; print(a); a = 4; print(a); to Lua interpreter 4 is printed on the screen. Then the program does other work. Later it feeds n = 0; for i=1,4 do n = n + i; end; print(n); n = 0; for i=1,4 do n = n + i; end; print(n); to the interpreter, and 10 is printed on the screen.

Note: All I want is that Lua interpreter execute the statements when my program feeds it one, while keeping its previous status. My program does not need to access variables in Lua interpreter.

I tried calling Lua interpreter separately, but it doesn't work as expected. Another solution is to record all previous statements, and run them before a new statement is going to run. But this is obviously not efficient.

Is there a easy way to do this? Such as just creating sub-process and making system calls?

As your question is very broad (interpret Lua or Python, in any language), I can only give you some hints.

If you write in C or C++, you can use the Lua library directly. It probably allows you to execute Lua statements, make values in C visible to the Lua code, make C function available to the Lua code, and access values of the Lua code.

If you write in Java, you may either write a JNI wrapper for the Lua library, or use another Lua implementation. See how can I embed lua in java? .

For other languages, you essentially have the same options: either use (if available) some other implementation in your favourite language, or find a way how you can access C library functions from your language. The latter is possible for most relevant programming languages.

For Python, the situation is similar. See, for example, Java Python Integration and Integrating Python With Other Languages .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM