r/learnpython • • 5d ago

how do i make an embedded lua interpreter?

im trying to make a project where in some parts you can run actual lua code. how would i make this and what libraries would i need (i already have lupa if that is usefull)

3 Upvotes

6 comments sorted by

2

u/lakseol 5d ago

Try searching on "lua in python". That finds things that you might be able to use, like this, amongst others:

https://luascripts.com/lua-in-python

1

u/ItsJustToastie 5d ago

i ment i would open a window with tkinter, then allow the user to code with lua in said window and run the code

2

u/lakseol 5d ago

For text-only output you could run the typed in code in a separate process that uses lua to execute the code, catch the text output and display that text in tkinter. Or have a look at:

https://luascripts.com/lua-in-python

which allows execution of lua code inside python. You would have to experiment with lupa to handle more than one lua statement. Maybe you could save the code into a temporary file and get lupa to execute that file.

1

u/RyanDubois43 5d ago

lupa.LuaRuntime() is what you want, then call.execute() on it to run lua code as a string. Remember that Lua variables and Python variables are not shared directly unless you pass them in.

1

u/Asly97 4d ago

lupa can do all of it in-process, no temp file or separate process needed. execute() takes the whole contents of your text box as one chunk, so multiple lines and functions are fine.

The part you need for a tkinter window is catching Lua's print, because by default it goes to the terminal and not your window. You can swap Lua's print for a Python function:

from lupa import LuaRuntime, LuaError

def run():
    lua = LuaRuntime(unpack_returned_tuples=True)

    def lua_print(*args):
        output.insert("end", " ".join(str(a) for a in args) + "\n")

    lua.globals().print = lua_print
    code = editor.get("1.0", "end")
    try:
        lua.execute(code)
    except LuaError as e:
        output.insert("end", f"error: {e}\n")

editor is the Text widget they type in, output is a second Text widget, and run goes on a Run button. Making a new LuaRuntime inside run means variables from the last run don't stick around.

Two things you'll hit pretty quickly:

  1. If someone writes while true do end, the whole window freezes, since the Lua runs on the same thread as tkinter. Before running their code you can do lua.execute('debug.sethook(function() error("took too long") end, "", 10000000)'), which throws an error after roughly 10 million instructions instead of hanging forever.
  2. If anyone other than you will type code into it, set lua.globals().os = None, lua.globals().io = None and lua.globals().debug = None (after setting the hook) so a script can't delete files or remove the hook.